View Javadoc
1   /*
2    * Copyright (c) 2002-2026 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit.css;
16  
17  import java.util.ArrayList;
18  import java.util.Collections;
19  import java.util.LinkedHashMap;
20  import java.util.List;
21  import java.util.Locale;
22  import java.util.Map;
23  import java.util.function.DoubleSupplier;
24  
25  import org.htmlunit.SilentCssErrorHandler;
26  import org.htmlunit.WebClient;
27  import org.htmlunit.WebClient.PooledCSS3Parser;
28  import org.htmlunit.cssparser.dom.CSSValueImpl;
29  import org.htmlunit.cssparser.parser.CSSOMParser;
30  import org.htmlunit.cssparser.parser.LexicalUnit;
31  import org.htmlunit.cssparser.parser.LexicalUnit.LexicalUnitType;
32  
33  /**
34   * Evaluates the CSS math functions {@code calc()}, {@code min()}, {@code max()} and
35   * {@code clamp()} for length values.
36   * <p>
37   * The value is parsed by the CSS parser; the resulting tree of lexical units (numbers,
38   * lengths, percentages, the operators {@code +}, {@code -}, {@code *} and {@code /},
39   * parentheses and nested math functions) is evaluated here. Lengths are converted to
40   * pixels using {@link CssPixelValueConverter#toPixels(double, String)}; percentages are
41   * resolved against the given base. Units are not type checked.
42   * </p>
43   *
44   * @author Ronald Brill
45   */
46  final class CssMathFunctionEvaluator {
47  
48      private static final int MAX_CACHE_SIZE = 500;
49  
50      /** The parsed values; the value is {@code null} if the value could not be parsed. */
51      private static final Map<String, LexicalUnit> PARSED = Collections.synchronizedMap(
52              new LinkedHashMap<>(16, 0.75f, true) {
53                  @Override
54                  protected boolean removeEldestEntry(final Map.Entry<String, LexicalUnit> eldest) {
55                      return size() > MAX_CACHE_SIZE;
56                  }
57              });
58  
59      private final DoubleSupplier percentBase_;
60  
61      private CssMathFunctionEvaluator(final DoubleSupplier percentBase) {
62          percentBase_ = percentBase;
63      }
64  
65      /**
66       * Returns whether the given value starts with a math function supported by this class.
67       *
68       * @param value the CSS value
69       * @return {@code true} if the value starts with {@code calc(}, {@code min(},
70       *         {@code max(} or {@code clamp(}
71       */
72      static boolean isMathFunction(final String value) {
73          if (value == null || value.isEmpty()) {
74              return false;
75          }
76          final String lower = value.trim().toLowerCase(Locale.ROOT);
77          return lower.startsWith("calc(")
78                  || lower.startsWith("min(")
79                  || lower.startsWith("max(")
80                  || lower.startsWith("clamp(");
81      }
82  
83      /**
84       * Evaluates the given math function.
85       *
86       * @param value the CSS value (e.g. {@code calc(100% - 20px)})
87       * @param webClient the web client providing the css parser; may be {@code null}
88       * @param percentBase supplier for the value (in pixels) that corresponds to 100%;
89       *        only called if the expression contains a percentage
90       * @return the value in pixels or {@code null} if the value is not supported
91       */
92      static Double evaluate(final String value, final WebClient webClient, final DoubleSupplier percentBase) {
93          final LexicalUnit unit = parse(value, webClient);
94          if (unit == null || unit.getNextLexicalUnit() != null) {
95              return null;
96          }
97  
98          try {
99              final double result = new CssMathFunctionEvaluator(percentBase).evaluateFunction(unit);
100             if (Double.isNaN(result) || Double.isInfinite(result)) {
101                 return null;
102             }
103             return result;
104         }
105         catch (final IllegalArgumentException e) {
106             return null;
107         }
108     }
109 
110     private static LexicalUnit parse(final String value, final WebClient webClient) {
111         LexicalUnit unit = PARSED.get(value);
112         if (unit == null && !PARSED.containsKey(value)) {
113             unit = parseValue(value, webClient);
114             // also cache unsupported values (null)
115             PARSED.put(value, unit);
116         }
117         return unit;
118     }
119 
120     private static LexicalUnit parseValue(final String value, final WebClient webClient) {
121         try {
122             final CSSValueImpl cssValue;
123             if (webClient == null) {
124                 final CSSOMParser parser = new CSSOMParser();
125                 parser.setErrorHandler(new SilentCssErrorHandler());
126                 cssValue = parser.parsePropertyValue(value);
127             }
128             else {
129                 // use a pooled parser to avoid the expensive creation
130                 try (PooledCSS3Parser pooledParser = webClient.getCSS3Parser()) {
131                     final CSSOMParser parser = new CSSOMParser(pooledParser);
132                     parser.setErrorHandler(new SilentCssErrorHandler());
133                     cssValue = parser.parsePropertyValue(value);
134                 }
135             }
136 
137             if (cssValue != null && cssValue.getValue() instanceof LexicalUnit unit) {
138                 return unit;
139             }
140         }
141         catch (final Exception e) {
142             // not supported
143         }
144         return null;
145     }
146 
147     private double evaluateFunction(final LexicalUnit function) {
148         final LexicalUnitType type = function.getLexicalUnitType();
149         final List<Double> args = evaluateArguments(function.getParameters());
150 
151         if (type == LexicalUnitType.FUNCTION_CALC
152                 || (type == LexicalUnitType.FUNCTION && function.getFunctionName().isEmpty())) {
153             // calc() or a parenthesized block
154             if (args.size() == 1) {
155                 return args.get(0);
156             }
157         }
158         else if (type == LexicalUnitType.FUNCTION_MIN) {
159             return args.stream().mapToDouble(Double::doubleValue).min().getAsDouble();
160         }
161         else if (type == LexicalUnitType.FUNCTION_MAX) {
162             return args.stream().mapToDouble(Double::doubleValue).max().getAsDouble();
163         }
164         else if (type == LexicalUnitType.FUNCTION_CLAMP) {
165             if (args.size() == 3) {
166                 return Math.max(args.get(0), Math.min(args.get(1), args.get(2)));
167             }
168         }
169         throw new IllegalArgumentException("Unsupported function '" + function + "'");
170     }
171 
172     /**
173      * Evaluates the comma separated arguments of a function.
174      */
175     private List<Double> evaluateArguments(final LexicalUnit params) {
176         if (params == null) {
177             throw new IllegalArgumentException("Arguments expected");
178         }
179 
180         final List<Double> args = new ArrayList<>();
181         final Cursor cursor = new Cursor(params);
182         args.add(evaluateSum(cursor));
183         while (cursor.is(LexicalUnitType.OPERATOR_COMMA)) {
184             cursor.next();
185             args.add(evaluateSum(cursor));
186         }
187         if (cursor.current_ != null) {
188             throw new IllegalArgumentException("Unexpected '" + cursor.current_ + "'");
189         }
190         return args;
191     }
192 
193     private double evaluateSum(final Cursor cursor) {
194         double result = evaluateProduct(cursor);
195         while (true) {
196             if (cursor.is(LexicalUnitType.OPERATOR_PLUS)) {
197                 cursor.next();
198                 result += evaluateProduct(cursor);
199             }
200             else if (cursor.is(LexicalUnitType.OPERATOR_MINUS)) {
201                 cursor.next();
202                 result -= evaluateProduct(cursor);
203             }
204             else {
205                 return result;
206             }
207         }
208     }
209 
210     private double evaluateProduct(final Cursor cursor) {
211         double result = evaluateValue(cursor);
212         while (true) {
213             if (cursor.is(LexicalUnitType.OPERATOR_MULTIPLY)) {
214                 cursor.next();
215                 result *= evaluateValue(cursor);
216             }
217             else if (cursor.is(LexicalUnitType.OPERATOR_SLASH)) {
218                 cursor.next();
219                 final double divisor = evaluateValue(cursor);
220                 if (divisor == 0) {
221                     throw new IllegalArgumentException("Division by zero");
222                 }
223                 result /= divisor;
224             }
225             else {
226                 return result;
227             }
228         }
229     }
230 
231     private double evaluateValue(final Cursor cursor) {
232         final LexicalUnit unit = cursor.current_;
233         if (unit == null) {
234             throw new IllegalArgumentException("Value expected");
235         }
236         cursor.next();
237 
238         switch (unit.getLexicalUnitType()) {
239             case INTEGER:
240                 return unit.getIntegerValue();
241 
242             case REAL:
243                 return unit.getDoubleValue();
244 
245             case PERCENTAGE:
246                 return unit.getDoubleValue() * percentBase_.getAsDouble() / 100;
247 
248             case PIXEL:
249             case EM:
250             case REM:
251             case EX:
252             case CH:
253             case VW:
254             case VH:
255             case VMIN:
256             case VMAX:
257             case DVW:
258             case DVH:
259             case DVMIN:
260             case DVMAX:
261             case LVW:
262             case LVH:
263             case LVMIN:
264             case LVMAX:
265             case SVW:
266             case SVH:
267             case SVMIN:
268             case SVMAX:
269             case INCH:
270             case CENTIMETER:
271             case MILLIMETER:
272             case POINT:
273             case PICA:
274                 return CssPixelValueConverter.toPixels(unit.getDoubleValue(), unit.getDimensionUnitText());
275 
276             case FUNCTION:
277             case FUNCTION_CALC:
278             case FUNCTION_MIN:
279             case FUNCTION_MAX:
280             case FUNCTION_CLAMP:
281                 return evaluateFunction(unit);
282 
283             default:
284                 // e.g. var() or an angle
285                 throw new IllegalArgumentException("Unsupported value '" + unit + "'");
286         }
287     }
288 
289     /**
290      * Iterates over a chain of lexical units.
291      */
292     private static final class Cursor {
293         private LexicalUnit current_;
294 
295         Cursor(final LexicalUnit first) {
296             current_ = first;
297         }
298 
299         boolean is(final LexicalUnitType type) {
300             return current_ != null && current_.getLexicalUnitType() == type;
301         }
302 
303         void next() {
304             current_ = current_.getNextLexicalUnit();
305         }
306     }
307 }