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 static org.htmlunit.css.CssStyleSheet.AUTO;
18  
19  import java.util.function.Function;
20  import java.util.function.IntSupplier;
21  import java.util.regex.Pattern;
22  
23  import org.htmlunit.html.DomElement;
24  import org.htmlunit.html.DomNode;
25  import org.htmlunit.html.HtmlCanvas;
26  import org.htmlunit.html.HtmlHtml;
27  import org.htmlunit.util.StringUtils;
28  
29  /**
30   * Utilities for css value handling.
31   *
32   * @author Ronald Brill
33   */
34  public final class CssPixelValueConverter {
35  
36      private static final Pattern TO_FLOAT_PATTERN = Pattern.compile("(\\d+(?:\\.\\d+)?).*");
37  
38      /**
39       * Disallow instantiation of this class.
40       */
41      private CssPixelValueConverter() {
42          // Empty.
43      }
44  
45      /**
46       * Converts the specified length CSS attribute value into an integer number of pixels. If the
47       * specified CSS attribute value is a percentage, this method uses the specified value getters
48       * to recursively retrieve the base (parent) CSS attribute value.
49       * @param element the element for which the CSS attribute value is to be retrieved
50       * @param styleGetter getter function to retrieve the CSS attribute value from ComputedCssStyleDeclaration
51       * @param defaultValue supplier for the default value
52       * @param windowDefaultValue supplier for the default value for the window
53       * @return the integer number of pixels corresponding to the specified length CSS attribute value
54       * @see #pixelValue(String)
55       */
56      public static int pixelValue(
57              final DomElement element,
58              final Function<ComputedCssStyleDeclaration, String> styleGetter,
59              final IntSupplier defaultValue,
60              final IntSupplier windowDefaultValue) {
61          final ComputedCssStyleDeclaration style =
62                  element.getPage().getEnclosingWindow().getComputedStyle(element, null);
63          final String s = styleGetter.apply(style);
64          return pixelValue(element, s, styleGetter, defaultValue, windowDefaultValue, false);
65      }
66  
67      /**
68       * Returns the specified length CSS attribute value as a pixel length value.
69       * If the specified CSS attribute value is a percentage, this method
70       * uses the specified value getters to recursively retrieve the base (parent) CSS attribute value.
71       * @param element the element for which the CSS attribute value is to be retrieved
72       * @param styleGetter getter function to retrieve the CSS attribute value from ComputedCssStyleDeclaration
73       * @param defaultValue supplier for the default value
74       * @param windowDefaultValue supplier for the default value for the window
75       * @return the specified length CSS attribute value as a pixel length value
76       * @see #pixelValue(DomElement, Function, IntSupplier, IntSupplier)
77       */
78      public static String pixelString(
79              final DomElement element,
80              final Function<ComputedCssStyleDeclaration, String> styleGetter,
81              final IntSupplier defaultValue,
82              final IntSupplier windowDefaultValue) {
83          final ComputedCssStyleDeclaration style =
84                  element.getPage().getEnclosingWindow().getComputedStyle(element, null);
85          final String styleValue = styleGetter.apply(style);
86          if (styleValue.endsWith("px")) {
87              return styleValue;
88          }
89          return pixelValue(element, styleValue, styleGetter, defaultValue, windowDefaultValue, false) + "px";
90      }
91  
92      /**
93       * Converts the specified length string value into an integer number of pixels. This method does
94       * <b>NOT</b> handle percentages correctly; use {@link #pixelString(DomElement, Function, IntSupplier, IntSupplier)}
95       * if you need percentage support.
96       * @param value the length string value to convert to an integer number of pixels
97       * @return the integer number of pixels corresponding to the specified length string value
98       * @see <a href="http://htmlhelp.com/reference/css/units.html">CSS Units</a>
99       * @see #pixelString(DomElement, Function, IntSupplier, IntSupplier)
100      */
101     public static int pixelValue(final String value) {
102         if (CssMathFunctionEvaluator.isMathFunction(value)) {
103             // like for simple percentages, 100% is 16px here
104             final Double result = CssMathFunctionEvaluator.evaluate(value, null, () -> 16);
105             return result == null ? 0 : (int) Math.round(result);
106         }
107 
108         final float i = StringUtils.toFloat(TO_FLOAT_PATTERN.matcher(value).replaceAll("$1"), 0);
109         if (value.length() < 2) {
110             return Math.round(i);
111         }
112         return (int) Math.round(toPixels(i, value));
113     }
114 
115     /**
116      * Converts the given number with the given unit into pixels.
117      * @param number the number
118      * @param unit the unit (e.g. {@code em}); percentages are based on 16px
119      * @return the number of pixels
120      */
121     static double toPixels(final double number, final String unit) {
122         if (unit.endsWith("px")) {
123             return number;
124         }
125         if (unit.endsWith("em")) {
126             return number * 16;
127         }
128         if (unit.endsWith("%")) {
129             return number * 16 / 100;
130         }
131         if (unit.endsWith("ex")) {
132             return number * 8;
133         }
134         if (unit.endsWith("cm")) {
135             return number * 38;
136         }
137         if (unit.endsWith("mm")) {
138             return number * 4;
139         }
140         if (unit.endsWith("pt")) {
141             return number * 2;
142         }
143         if (unit.endsWith("pc")) {
144             return number * 24;
145         }
146         if (unit.endsWith("ch")) {
147             return number * 8;
148         }
149         if (unit.endsWith("vh")
150                 || unit.endsWith("vmin")) {
151             // this matches also
152             // "dvh" "dvmin" "lvh" "lvmin" "svh" "svmin"
153             return number * 6;
154         }
155         if (unit.endsWith("vw")
156                 || unit.endsWith("vmax")) {
157             // this matches also
158             // "dvw" "dvmax" "lvw" "lvmax" "svw" "svmax"
159             return number * 12;
160         }
161         // placed at the end to handle min before
162         if (unit.endsWith("in")) {
163             return number * 150;
164         }
165         return number;
166     }
167 
168     private static int pixelValue(final DomElement element,
169             final String styleValue,
170             final Function<ComputedCssStyleDeclaration, String> styleGetter,
171             final IntSupplier defaultValue,
172             final IntSupplier windowDefaultValue,
173             final boolean percentMode) {
174         if (CssMathFunctionEvaluator.isMathFunction(styleValue)) {
175             final Double result = CssMathFunctionEvaluator.evaluate(styleValue, element.getPage().getWebClient(),
176                     () -> percentBase(element, styleGetter, defaultValue, windowDefaultValue));
177             return result == null ? 0 : (int) Math.round(result);
178         }
179 
180         if (styleValue.endsWith("%") || (styleValue.isEmpty() && element instanceof HtmlHtml)) {
181             final float i = StringUtils.toFloat(TO_FLOAT_PATTERN.matcher(styleValue).replaceAll("$1"), 100);
182             final int absoluteValue = percentBase(element, styleGetter, defaultValue, windowDefaultValue);
183             return Math.round((i / 100f) * absoluteValue);
184         }
185         if (AUTO.equals(styleValue)) {
186             return defaultValue.getAsInt();
187         }
188         if (styleValue.isEmpty()) {
189             if (element instanceof HtmlCanvas) {
190                 return windowDefaultValue.getAsInt();
191             }
192 
193             // if the call was originated from a percent value we have to go up until
194             // we can provide some kind of base value for percent calculation
195             if (percentMode) {
196                 final DomNode parent = element.getParentNode();
197                 if (parent == null || parent instanceof HtmlHtml) {
198                     return windowDefaultValue.getAsInt();
199                 }
200                 final DomElement parentElem = (DomElement) parent;
201                 final ComputedCssStyleDeclaration style =
202                         parentElem.getPage().getEnclosingWindow().getComputedStyle(parentElem, null);
203                 final String parentStyleValue = styleGetter.apply(style);
204                 return pixelValue(parentElem, parentStyleValue, styleGetter, defaultValue, windowDefaultValue, true);
205             }
206 
207             return 0;
208         }
209         return pixelValue(styleValue);
210     }
211 
212     /**
213      * Returns the value (in pixels) a percentage of the given element is based on;
214      * this is the value of the parent or the window default value for the root.
215      */
216     private static int percentBase(final DomElement element,
217             final Function<ComputedCssStyleDeclaration, String> styleGetter,
218             final IntSupplier defaultValue,
219             final IntSupplier windowDefaultValue) {
220         final DomNode parent = element.getParentNode();
221         if (parent instanceof DomElement parentElem) {
222             final ComputedCssStyleDeclaration style =
223                     parentElem.getPage().getEnclosingWindow().getComputedStyle(parentElem, null);
224             final String parentStyleValue = styleGetter.apply(style);
225             return pixelValue(parentElem, parentStyleValue, styleGetter,
226                                         defaultValue, windowDefaultValue, true);
227         }
228         return windowDefaultValue.getAsInt();
229     }
230 }