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.javascript.host.dom;
16  
17  import java.util.ArrayList;
18  import java.util.List;
19  import java.util.Locale;
20  import java.util.regex.Matcher;
21  import java.util.regex.Pattern;
22  
23  /**
24   * Parser for the CSS transform lists used by the {@link DOMMatrixReadOnly} and {@link DOMMatrix}
25   * constructors and by {@link DOMMatrix#setMatrixValue(String)}.
26   *
27   * <p>Supported are the empty string and {@code none} (the identity matrix) and a list of the
28   * transform functions {@code matrix()}, {@code matrix3d()}, {@code translate()}, {@code translateX()},
29   * {@code translateY()}, {@code translateZ()}, {@code translate3d()}, {@code scale()}, {@code scaleX()},
30   * {@code scaleY()}, {@code scaleZ()}, {@code scale3d()}, {@code rotate()}, {@code rotateX()},
31   * {@code rotateY()}, {@code rotateZ()}, {@code rotate3d()}, {@code skew()}, {@code skewX()},
32   * {@code skewY()} and {@code perspective()}.</p>
33   *
34   * <p>Lengths can have the absolute units {@code px}, {@code cm}, {@code mm}, {@code q},
35   * {@code in}, {@code pt} and {@code pc}; angles the units {@code deg}, {@code rad},
36   * {@code grad} and {@code turn}. A length or angle without unit is only allowed for 0.
37   * Relative units (e.g. {@code em} or percentages for lengths) can't be resolved without an element;
38   * like in the browsers, they are a syntax error. Scale factors can be numbers or percentages.</p>
39   *
40   * <p>If one of the functions is a 3D function, the resulting matrix is 3D (even if the values
41   * would allow a 2D matrix); like in the browsers, {@code rotateZ()} counts as 2D function.
42   * Like in CSS, the end of the input closes a function that is still open.</p>
43   *
44   * @author Ronald Brill
45   */
46  final class DOMMatrixTransformListParser {
47  
48      private static final Pattern NUMBER_PATTERN =
49              Pattern.compile("([+-]?(?:\\d*\\.\\d+|\\d+)(?:[eE][+-]?\\d+)?)([a-zA-Z]*|%)");
50  
51      private enum ArgumentType {
52          NUMBER, NUMBER_OR_PERCENTAGE, LENGTH, ANGLE
53      }
54  
55      private DOMMatrixTransformListParser() {
56          // util class
57      }
58  
59      /**
60       * Parses the given transform list and replaces the values of the given matrix with the result.
61       *
62       * @param transformList the transform list
63       * @param matrix the matrix to set the result to
64       * @throws IllegalArgumentException if the transform list is not valid
65       */
66      static void parse(final String transformList, final DOMMatrixReadOnly matrix) {
67          final DOMMatrixReadOnly result = new DOMMatrixReadOnly();
68  
69          final String text = trimCssWhitespace(transformList);
70          if (text.isEmpty() || "none".equalsIgnoreCase(text)) {
71              matrix.setValues(result.getValues(), true);
72              return;
73          }
74  
75          boolean is3D = false;
76          int pos = 0;
77          while (pos < text.length()) {
78              final int open = text.indexOf('(', pos);
79              if (open < 0) {
80                  throw new IllegalArgumentException("transform function expected at position " + pos);
81              }
82              final String name = text.substring(pos, open).toLowerCase(Locale.ROOT);
83              if (!name.matches("[a-z][a-z0-9]*")) {
84                  throw new IllegalArgumentException("invalid transform function '" + name + "'");
85              }
86  
87              // like in CSS, the end of the input closes the last function
88              int close = text.indexOf(')', open);
89              if (close < 0) {
90                  close = text.length();
91              }
92  
93              is3D |= apply(name, splitArguments(text.substring(open + 1, close)), result);
94  
95              pos = close + 1;
96              while (pos < text.length() && isCssWhitespace(text.charAt(pos))) {
97                  pos++;
98              }
99          }
100 
101         matrix.setValues(result.getValues(), result.isIs2D() && !is3D);
102     }
103 
104     /**
105      * Applies the given transform function to the matrix.
106      *
107      * @param name the function name (lower case)
108      * @param args the arguments
109      * @param matrix the matrix
110      * @return true if this is a 3D function
111      */
112     private static boolean apply(final String name, final List<String> args, final DOMMatrixReadOnly matrix) {
113         switch (name) {
114             case "matrix": {
115                 final double[] v = values(name, args, 6, 6, ArgumentType.NUMBER);
116                 final DOMMatrixReadOnly other = new DOMMatrixReadOnly();
117                 other.setValues2D(v[0], v[1], v[2], v[3], v[4], v[5]);
118                 matrix.multiplySelfInternal(other);
119                 return false;
120             }
121             case "matrix3d": {
122                 final double[] v = values(name, args, 16, 16, ArgumentType.NUMBER);
123                 final DOMMatrixReadOnly other = new DOMMatrixReadOnly();
124                 other.setValues(v, false);
125                 matrix.multiplySelfInternal(other);
126                 return true;
127             }
128 
129             case "translate": {
130                 final double[] v = values(name, args, 1, 2, ArgumentType.LENGTH);
131                 matrix.translateSelfInternal(v[0], v.length > 1 ? v[1] : 0, 0);
132                 return false;
133             }
134             case "translatex":
135                 matrix.translateSelfInternal(values(name, args, 1, 1, ArgumentType.LENGTH)[0], 0, 0);
136                 return false;
137             case "translatey":
138                 matrix.translateSelfInternal(0, values(name, args, 1, 1, ArgumentType.LENGTH)[0], 0);
139                 return false;
140             case "translatez":
141                 matrix.translateSelfInternal(0, 0, values(name, args, 1, 1, ArgumentType.LENGTH)[0]);
142                 return true;
143             case "translate3d": {
144                 final double[] v = values(name, args, 3, 3, ArgumentType.LENGTH);
145                 matrix.translateSelfInternal(v[0], v[1], v[2]);
146                 return true;
147             }
148 
149             case "scale": {
150                 final double[] v = values(name, args, 1, 2, ArgumentType.NUMBER_OR_PERCENTAGE);
151                 matrix.scaleSelfInternal(v[0], v.length > 1 ? v[1] : v[0], 1, 0, 0, 0);
152                 return false;
153             }
154             case "scalex":
155                 matrix.scaleSelfInternal(values(name, args, 1, 1, ArgumentType.NUMBER_OR_PERCENTAGE)[0],
156                         1, 1, 0, 0, 0);
157                 return false;
158             case "scaley":
159                 matrix.scaleSelfInternal(1, values(name, args, 1, 1, ArgumentType.NUMBER_OR_PERCENTAGE)[0],
160                         1, 0, 0, 0);
161                 return false;
162             case "scalez":
163                 matrix.scaleSelfInternal(1, 1, values(name, args, 1, 1, ArgumentType.NUMBER_OR_PERCENTAGE)[0],
164                         0, 0, 0);
165                 return true;
166             case "scale3d": {
167                 final double[] v = values(name, args, 3, 3, ArgumentType.NUMBER_OR_PERCENTAGE);
168                 matrix.scaleSelfInternal(v[0], v[1], v[2], 0, 0, 0);
169                 return true;
170             }
171 
172             case "rotate":
173                 matrix.rotateSelfInternal(0, 0, values(name, args, 1, 1, ArgumentType.ANGLE)[0]);
174                 return false;
175             case "rotatez":
176                 // the browsers are treating this as 2D function
177                 matrix.rotateSelfInternal(0, 0, values(name, args, 1, 1, ArgumentType.ANGLE)[0]);
178                 return false;
179             case "rotatex":
180                 matrix.rotateAxisAngleSelfInternal(1, 0, 0, values(name, args, 1, 1, ArgumentType.ANGLE)[0]);
181                 return true;
182             case "rotatey":
183                 matrix.rotateAxisAngleSelfInternal(0, 1, 0, values(name, args, 1, 1, ArgumentType.ANGLE)[0]);
184                 return true;
185             case "rotate3d": {
186                 if (args.size() != 4) {
187                     throw new IllegalArgumentException("rotate3d() requires 4 arguments");
188                 }
189                 final double x = value(args.get(0), ArgumentType.NUMBER);
190                 final double y = value(args.get(1), ArgumentType.NUMBER);
191                 final double z = value(args.get(2), ArgumentType.NUMBER);
192                 final double angle = value(args.get(3), ArgumentType.ANGLE);
193                 matrix.rotateAxisAngleSelfInternal(x, y, z, angle);
194                 return true;
195             }
196 
197             case "skew": {
198                 final double[] v = values(name, args, 1, 2, ArgumentType.ANGLE);
199                 final DOMMatrixReadOnly skew = new DOMMatrixReadOnly();
200                 skew.setValues2D(1, Math.tan(Math.toRadians(v.length > 1 ? v[1] : 0)),
201                         Math.tan(Math.toRadians(v[0])), 1, 0, 0);
202                 matrix.multiplySelfInternal(skew);
203                 return false;
204             }
205             case "skewx":
206                 matrix.skewXSelfInternal(values(name, args, 1, 1, ArgumentType.ANGLE)[0]);
207                 return false;
208             case "skewy":
209                 matrix.skewYSelfInternal(values(name, args, 1, 1, ArgumentType.ANGLE)[0]);
210                 return false;
211 
212             case "perspective": {
213                 if (args.size() != 1) {
214                     throw new IllegalArgumentException("perspective() requires 1 argument");
215                 }
216                 if ("none".equalsIgnoreCase(args.get(0))) {
217                     return true;
218                 }
219                 final double length = value(args.get(0), ArgumentType.LENGTH);
220                 if (length < 0) {
221                     throw new IllegalArgumentException("perspective() requires a non-negative length");
222                 }
223                 final DOMMatrixReadOnly perspective = new DOMMatrixReadOnly();
224                 final double[] v = perspective.getValues();
225                 // values below 1px are treated as 1px
226                 v[11] = -1 / Math.max(1, length);
227                 perspective.setValues(v, false);
228                 matrix.multiplySelfInternal(perspective);
229                 return true;
230             }
231 
232             default:
233                 throw new IllegalArgumentException("unknown transform function '" + name + "'");
234         }
235     }
236 
237     private static double[] values(final String name, final List<String> args, final int min, final int max,
238             final ArgumentType type) {
239         if (args.size() < min || args.size() > max) {
240             throw new IllegalArgumentException(name + "() requires "
241                     + (min == max ? Integer.toString(min) : min + " to " + max) + " arguments");
242         }
243 
244         final double[] result = new double[args.size()];
245         for (int i = 0; i < result.length; i++) {
246             result[i] = value(args.get(i), type);
247         }
248         return result;
249     }
250 
251     /**
252      * Parses one argument.
253      *
254      * @param arg the argument
255      * @param type the expected type
256      * @return the value; lengths in px, angles in degrees, percentages as factor
257      */
258     private static double value(final String arg, final ArgumentType type) {
259         final Matcher matcher = NUMBER_PATTERN.matcher(arg);
260         if (!matcher.matches()) {
261             throw new IllegalArgumentException("invalid value '" + arg + "'");
262         }
263 
264         final double number = Double.parseDouble(matcher.group(1));
265         final String unit = matcher.group(2).toLowerCase(Locale.ROOT);
266 
267         switch (type) {
268             case NUMBER:
269                 if (unit.isEmpty()) {
270                     return number;
271                 }
272                 break;
273 
274             case NUMBER_OR_PERCENTAGE:
275                 if (unit.isEmpty()) {
276                     return number;
277                 }
278                 if ("%".equals(unit)) {
279                     return number / 100;
280                 }
281                 break;
282 
283             case LENGTH: {
284                 if (unit.isEmpty() && number == 0) {
285                     return 0;
286                 }
287                 final double factor = lengthFactor(unit);
288                 if (factor > 0) {
289                     return number * factor;
290                 }
291                 break;
292             }
293 
294             case ANGLE:
295                 if (unit.isEmpty() && number == 0) {
296                     return 0;
297                 }
298                 switch (unit) {
299                     case "deg":
300                         return number;
301                     case "rad":
302                         return Math.toDegrees(number);
303                     case "grad":
304                         return number * 0.9;
305                     case "turn":
306                         return number * 360;
307                     default:
308                         break;
309                 }
310                 break;
311 
312             default:
313                 break;
314         }
315 
316         throw new IllegalArgumentException("invalid value '" + arg + "'");
317     }
318 
319     private static double lengthFactor(final String unit) {
320         return switch (unit) {
321             case "px" -> 1;
322             case "in" -> 96;
323             case "cm" -> 96 / 2.54;
324             case "mm" -> 96 / 25.4;
325             case "q" -> 96 / 101.6;
326             case "pt" -> 96.0 / 72;
327             case "pc" -> 16;
328             default -> -1;
329         };
330     }
331 
332     private static List<String> splitArguments(final String args) {
333         final List<String> result = new ArrayList<>();
334         for (final String arg : args.split(",", -1)) {
335             final String trimmed = trimCssWhitespace(arg);
336             if (trimmed.isEmpty()) {
337                 throw new IllegalArgumentException("empty argument");
338             }
339             result.add(trimmed);
340         }
341         return result;
342     }
343 
344     private static String trimCssWhitespace(final String text) {
345         int start = 0;
346         int end = text.length();
347         while (start < end && isCssWhitespace(text.charAt(start))) {
348             start++;
349         }
350         while (end > start && isCssWhitespace(text.charAt(end - 1))) {
351             end--;
352         }
353         return text.substring(start, end);
354     }
355 
356     private static boolean isCssWhitespace(final char c) {
357         return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
358     }
359 }