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.platform.canvas.rendering;
16  
17  import java.awt.AlphaComposite;
18  import java.awt.BasicStroke;
19  import java.awt.Color;
20  import java.awt.Composite;
21  import java.awt.Font;
22  import java.awt.FontMetrics;
23  import java.awt.Graphics2D;
24  import java.awt.RenderingHints;
25  import java.awt.Shape;
26  import java.awt.geom.AffineTransform;
27  import java.awt.geom.Arc2D;
28  import java.awt.geom.Path2D;
29  import java.awt.geom.PathIterator;
30  import java.awt.geom.Point2D;
31  import java.awt.image.BufferedImage;
32  import java.io.ByteArrayOutputStream;
33  import java.io.IOException;
34  import java.nio.ByteBuffer;
35  import java.nio.charset.StandardCharsets;
36  import java.util.ArrayDeque;
37  import java.util.ArrayList;
38  import java.util.Base64;
39  import java.util.Deque;
40  import java.util.HashMap;
41  import java.util.List;
42  import java.util.Locale;
43  import java.util.Map;
44  import java.util.concurrent.atomic.AtomicInteger;
45  
46  import javax.imageio.ImageIO;
47  import javax.imageio.ImageReader;
48  
49  import org.apache.commons.logging.Log;
50  import org.apache.commons.logging.LogFactory;
51  import org.htmlunit.platform.image.ImageIOImageData;
52  import org.htmlunit.util.StringUtils;
53  
54  /**
55   * The default implementation of {@link RenderingBackend}.
56   *
57   * @author Ronald Brill
58   */
59  public class AwtRenderingBackend implements RenderingBackend {
60  
61      private static final Log LOG = LogFactory.getLog(AwtRenderingBackend.class);
62      private static final AtomicInteger ID_GENERATOR = new AtomicInteger();
63  
64      private static final Map<String, Color> KNOWN_COLORS = new HashMap<>();
65  
66      private final int id_;
67      private final BufferedImage image_;
68      private final Graphics2D graphics2D_;
69  
70      private AffineTransform transformation_;
71      private float globalAlpha_;
72      private float lineWidth_;
73      private Color fillColor_;
74      private Color strokeColor_;
75  
76      private LineCap lineCap_;
77      private LineJoin lineJoin_;
78      private float miterLimit_;
79  
80      private TextAlign textAlign_;
81      private TextBaseline textBaseline_;
82  
83      private final List<Path2D> subPaths_;
84      private final Deque<SaveState> savedStates_;
85  
86      static {
87          // see https://developer.mozilla.org/en-US/docs/Web/CSS/color_value
88  
89          // CSS Level 1
90          KNOWN_COLORS.put("black", Color.decode("#000000"));
91          KNOWN_COLORS.put("silver", Color.decode("#c0c0c0"));
92          KNOWN_COLORS.put("gray", Color.decode("#808080"));
93          KNOWN_COLORS.put("white", Color.decode("#ffffff"));
94          KNOWN_COLORS.put("maroon", Color.decode("#800000"));
95          KNOWN_COLORS.put("red", Color.decode("#ff0000"));
96          KNOWN_COLORS.put("purple", Color.decode("#800080"));
97          KNOWN_COLORS.put("fuchsia", Color.decode("#ff00ff"));
98          KNOWN_COLORS.put("green", Color.decode("#008000"));
99          KNOWN_COLORS.put("lime", Color.decode("#00ff00"));
100         KNOWN_COLORS.put("olive", Color.decode("#808000"));
101         KNOWN_COLORS.put("yellow", Color.decode("#ffff00"));
102         KNOWN_COLORS.put("navy", Color.decode("#000080"));
103         KNOWN_COLORS.put("blue", Color.decode("#0000ff"));
104         KNOWN_COLORS.put("teal", Color.decode("#008080"));
105         KNOWN_COLORS.put("aqua", Color.decode("#00ffff"));
106 
107         // CSS Level 2 (Revision 1)
108         KNOWN_COLORS.put("orange", Color.decode("#ffa500"));
109 
110         // CSS Color Module Level 3
111         KNOWN_COLORS.put("aliceblue", Color.decode("#f0f8ff"));
112         KNOWN_COLORS.put("antiquewhite", Color.decode("#faebd7"));
113         KNOWN_COLORS.put("aquamarine", Color.decode("#7fffd4"));
114         KNOWN_COLORS.put("azure", Color.decode("#f0ffff"));
115         KNOWN_COLORS.put("beige", Color.decode("#f5f5dc"));
116         KNOWN_COLORS.put("bisque", Color.decode("#ffe4c4"));
117         KNOWN_COLORS.put("blanchedalmond", Color.decode("#ffebcd"));
118         KNOWN_COLORS.put("blueviolet", Color.decode("#8a2be2"));
119         KNOWN_COLORS.put("brown", Color.decode("#a52a2a"));
120         KNOWN_COLORS.put("burlywood", Color.decode("#deb887"));
121         KNOWN_COLORS.put("cadetblue", Color.decode("#5f9ea0"));
122         KNOWN_COLORS.put("chartreuse", Color.decode("#7fff00"));
123         KNOWN_COLORS.put("chocolate", Color.decode("#d2691e"));
124         KNOWN_COLORS.put("coral", Color.decode("#ff7f50"));
125         KNOWN_COLORS.put("cornflowerblue", Color.decode("#6495ed"));
126         KNOWN_COLORS.put("cornsilk", Color.decode("#fff8dc"));
127         KNOWN_COLORS.put("crimson", Color.decode("#dc143c"));
128         KNOWN_COLORS.put("cyan", Color.decode("#00ffff")); // synonym of aqua
129         KNOWN_COLORS.put("darkblue", Color.decode("#00008b"));
130         KNOWN_COLORS.put("darkcyan", Color.decode("#008b8b"));
131         KNOWN_COLORS.put("darkgoldenrod", Color.decode("#b8860b"));
132         KNOWN_COLORS.put("darkgray", Color.decode("#a9a9a9"));
133         KNOWN_COLORS.put("darkgreen", Color.decode("#006400"));
134         KNOWN_COLORS.put("darkgrey", Color.decode("#a9a9a9"));
135         KNOWN_COLORS.put("darkkhaki", Color.decode("#bdb76b"));
136         KNOWN_COLORS.put("darkmagenta", Color.decode("#8b008b"));
137         KNOWN_COLORS.put("darkolivegreen", Color.decode("#556b2f"));
138         KNOWN_COLORS.put("darkorange", Color.decode("#ff8c00"));
139         KNOWN_COLORS.put("darkorchid", Color.decode("#9932cc"));
140         KNOWN_COLORS.put("darkred", Color.decode("#8b0000"));
141         KNOWN_COLORS.put("darksalmon", Color.decode("#e9967a"));
142         KNOWN_COLORS.put("darkseagreen", Color.decode("#8fbc8f"));
143         KNOWN_COLORS.put("darkslateblue", Color.decode("#483d8b"));
144         KNOWN_COLORS.put("darkslategray", Color.decode("#2f4f4f"));
145         KNOWN_COLORS.put("darkslategrey", Color.decode("#2f4f4f"));
146         KNOWN_COLORS.put("darkturquoise", Color.decode("#00ced1"));
147         KNOWN_COLORS.put("darkviolet", Color.decode("#9400d3"));
148         KNOWN_COLORS.put("deeppink", Color.decode("#ff1493"));
149         KNOWN_COLORS.put("deepskyblue", Color.decode("#00bfff"));
150         KNOWN_COLORS.put("dimgray", Color.decode("#696969"));
151         KNOWN_COLORS.put("dimgrey", Color.decode("#696969"));
152         KNOWN_COLORS.put("dodgerblue", Color.decode("#1e90ff"));
153         KNOWN_COLORS.put("firebrick", Color.decode("#b22222"));
154         KNOWN_COLORS.put("floralwhite", Color.decode("#fffaf0"));
155         KNOWN_COLORS.put("forestgreen", Color.decode("#228b22"));
156         KNOWN_COLORS.put("gainsboro", Color.decode("#dcdcdc"));
157         KNOWN_COLORS.put("ghostwhite", Color.decode("#f8f8ff"));
158         KNOWN_COLORS.put("gold", Color.decode("#ffd700"));
159         KNOWN_COLORS.put("goldenrod", Color.decode("#daa520"));
160         KNOWN_COLORS.put("greenyellow", Color.decode("#adff2f"));
161         KNOWN_COLORS.put("grey", Color.decode("#808080"));
162         KNOWN_COLORS.put("honeydew", Color.decode("#f0fff0"));
163         KNOWN_COLORS.put("hotpink", Color.decode("#ff69b4"));
164         KNOWN_COLORS.put("indianred", Color.decode("#cd5c5c"));
165         KNOWN_COLORS.put("indigo", Color.decode("#4b0082"));
166         KNOWN_COLORS.put("ivory", Color.decode("#fffff0"));
167         KNOWN_COLORS.put("khaki", Color.decode("#f0e68c"));
168         KNOWN_COLORS.put("lavender", Color.decode("#e6e6fa"));
169         KNOWN_COLORS.put("lavenderblush", Color.decode("#fff0f5"));
170         KNOWN_COLORS.put("lawngreen", Color.decode("#7cfc00"));
171         KNOWN_COLORS.put("lemonchiffon", Color.decode("#fffacd"));
172         KNOWN_COLORS.put("lightblue", Color.decode("#add8e6"));
173         KNOWN_COLORS.put("lightcoral", Color.decode("#f08080"));
174         KNOWN_COLORS.put("lightcyan", Color.decode("#e0ffff"));
175         KNOWN_COLORS.put("lightgoldenrodyellow", Color.decode("#fafad2"));
176         KNOWN_COLORS.put("lightgray", Color.decode("#d3d3d3"));
177         KNOWN_COLORS.put("lightgreen", Color.decode("#90ee90"));
178         KNOWN_COLORS.put("lightgrey", Color.decode("#d3d3d3"));
179         KNOWN_COLORS.put("lightpink", Color.decode("#ffb6c1"));
180         KNOWN_COLORS.put("lightsalmon", Color.decode("#ffa07a"));
181         KNOWN_COLORS.put("lightseagreen", Color.decode("#20b2aa"));
182         KNOWN_COLORS.put("lightskyblue", Color.decode("#87cefa"));
183         KNOWN_COLORS.put("lightslategray", Color.decode("#778899"));
184         KNOWN_COLORS.put("lightslategrey", Color.decode("#778899"));
185         KNOWN_COLORS.put("lightsteelblue", Color.decode("#b0c4de"));
186         KNOWN_COLORS.put("lightyellow", Color.decode("#ffffe0"));
187         KNOWN_COLORS.put("limegreen", Color.decode("#32cd32"));
188         KNOWN_COLORS.put("linen", Color.decode("#faf0e6"));
189         KNOWN_COLORS.put("magenta", Color.decode("#ff00ff")); // synonym of fuchsia
190         KNOWN_COLORS.put("mediumaquamarine", Color.decode("#66cdaa"));
191         KNOWN_COLORS.put("mediumblue", Color.decode("#0000cd"));
192         KNOWN_COLORS.put("mediumorchid", Color.decode("#ba55d3"));
193         KNOWN_COLORS.put("mediumpurple", Color.decode("#9370db"));
194         KNOWN_COLORS.put("mediumseagreen", Color.decode("#3cb371"));
195         KNOWN_COLORS.put("mediumslateblue", Color.decode("#7b68ee"));
196         KNOWN_COLORS.put("mediumspringgreen", Color.decode("#00fa9a"));
197         KNOWN_COLORS.put("mediumturquoise", Color.decode("#48d1cc"));
198         KNOWN_COLORS.put("mediumvioletred", Color.decode("#c71585"));
199         KNOWN_COLORS.put("midnightblue", Color.decode("#191970"));
200         KNOWN_COLORS.put("mintcream", Color.decode("#f5fffa"));
201         KNOWN_COLORS.put("mistyrose", Color.decode("#ffe4e1"));
202         KNOWN_COLORS.put("moccasin", Color.decode("#ffe4b5"));
203         KNOWN_COLORS.put("navajowhite", Color.decode("#ffdead"));
204         KNOWN_COLORS.put("oldlace", Color.decode("#fdf5e6"));
205         KNOWN_COLORS.put("olivedrab", Color.decode("#6b8e23"));
206         KNOWN_COLORS.put("orangered", Color.decode("#ff4500"));
207         KNOWN_COLORS.put("orchid", Color.decode("#da70d6"));
208         KNOWN_COLORS.put("palegoldenrod", Color.decode("#eee8aa"));
209         KNOWN_COLORS.put("palegreen", Color.decode("#98fb98"));
210         KNOWN_COLORS.put("paleturquoise", Color.decode("#afeeee"));
211         KNOWN_COLORS.put("palevioletred", Color.decode("#db7093"));
212         KNOWN_COLORS.put("papayawhip", Color.decode("#ffefd5"));
213         KNOWN_COLORS.put("peachpuff", Color.decode("#ffdab9"));
214         KNOWN_COLORS.put("peru", Color.decode("#cd853f"));
215         KNOWN_COLORS.put("pink", Color.decode("#ffc0cb"));
216         KNOWN_COLORS.put("plum", Color.decode("#dda0dd"));
217         KNOWN_COLORS.put("powderblue", Color.decode("#b0e0e6"));
218         KNOWN_COLORS.put("rosybrown", Color.decode("#bc8f8f"));
219         KNOWN_COLORS.put("royalblue", Color.decode("#4169e1"));
220         KNOWN_COLORS.put("saddlebrown", Color.decode("#8b4513"));
221         KNOWN_COLORS.put("salmon", Color.decode("#fa8072"));
222         KNOWN_COLORS.put("sandybrown", Color.decode("#f4a460"));
223         KNOWN_COLORS.put("seagreen", Color.decode("#2e8b57"));
224         KNOWN_COLORS.put("seashell", Color.decode("#fff5ee"));
225         KNOWN_COLORS.put("sienna", Color.decode("#a0522d"));
226         KNOWN_COLORS.put("skyblue", Color.decode("#87ceeb"));
227         KNOWN_COLORS.put("slateblue", Color.decode("#6a5acd"));
228         KNOWN_COLORS.put("slategray", Color.decode("#708090"));
229         KNOWN_COLORS.put("slategrey", Color.decode("#708090"));
230         KNOWN_COLORS.put("snow", Color.decode("#fffafa"));
231         KNOWN_COLORS.put("springgreen", Color.decode("#00ff7f"));
232         KNOWN_COLORS.put("steelblue", Color.decode("#4682b4"));
233         KNOWN_COLORS.put("tan", Color.decode("#d2b48c"));
234         KNOWN_COLORS.put("thistle", Color.decode("#d8bfd8"));
235         KNOWN_COLORS.put("tomato", Color.decode("#ff6347"));
236         KNOWN_COLORS.put("turquoise", Color.decode("#40e0d0"));
237         KNOWN_COLORS.put("violet", Color.decode("#ee82ee"));
238         KNOWN_COLORS.put("wheat", Color.decode("#f5deb3"));
239         KNOWN_COLORS.put("whitesmoke", Color.decode("#f5f5f5"));
240         KNOWN_COLORS.put("yellowgreen", Color.decode("#9acd32"));
241         // CSS Color Module Level 4
242         KNOWN_COLORS.put("rebeccapurple", Color.decode("#663399"));
243     }
244 
245     /**
246      * Constructor.
247      * @param imageWidth the width
248      * @param imageHeight the height
249      */
250     public AwtRenderingBackend(final int imageWidth, final int imageHeight) {
251         id_ = ID_GENERATOR.getAndIncrement();
252         if (LOG.isDebugEnabled()) {
253             LOG.debug("[" + id_ + "] AwtRenderingBackend(" + imageWidth + ", " + imageHeight + ")");
254         }
255 
256         image_ = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB);
257         graphics2D_ = image_.createGraphics();
258 
259         graphics2D_.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
260         graphics2D_.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
261         graphics2D_.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
262 
263         // without this AWT snaps strokes to pixel boundaries (hence the floor rounding).
264         // With VALUE_STROKE_PURE, strokes are rendered at their exact fractional coordinates,
265         // matching browser sub-pixel behavior.
266         graphics2D_.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
267 
268         // reset
269         fillColor_ = Color.black;
270         strokeColor_ = Color.black;
271         lineWidth_ = 1;
272         transformation_ = new AffineTransform();
273         updateGlobalAlpha(1f);
274         graphics2D_.setClip(null);
275 
276         final Font font = new Font("SansSerif", Font.PLAIN, 10);
277         graphics2D_.setFont(font);
278 
279         graphics2D_.setBackground(new Color(0f, 0f, 0f, 0f));
280         graphics2D_.setColor(Color.black);
281         graphics2D_.clearRect(0, 0, imageWidth, imageHeight);
282 
283         lineCap_ = LineCap.BUTT;
284         lineJoin_ = LineJoin.MITER;
285         miterLimit_ = 10.0f;
286 
287         textAlign_ = TextAlign.START;
288         textBaseline_ = TextBaseline.ALPHABETIC;
289 
290         subPaths_ = new ArrayList<>();
291         savedStates_ = new ArrayDeque<>();
292     }
293 
294     /**
295      * {@inheritDoc}
296      */
297     @Override
298     public double getGlobalAlpha() {
299         return globalAlpha_;
300     }
301 
302     /**
303      * {@inheritDoc}
304      */
305     @Override
306     public void setGlobalAlpha(final double globalAlpha) {
307         if (LOG.isDebugEnabled()) {
308             LOG.debug("[" + id_ + "] setGlobalAlpha(" + globalAlpha + ")");
309         }
310 
311         if (globalAlpha >= 0 && globalAlpha <= 1) {
312             updateGlobalAlpha((float) globalAlpha);
313         }
314     }
315 
316     private void updateGlobalAlpha(final float globalAlpha) {
317         globalAlpha_ = globalAlpha;
318         final AlphaComposite composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, globalAlpha_);
319         graphics2D_.setComposite(composite);
320     }
321 
322     /**
323      * {@inheritDoc}
324      */
325     @Override
326     public void beginPath() {
327         if (LOG.isDebugEnabled()) {
328             LOG.debug("[" + id_ + "] beginPath()");
329         }
330         subPaths_.clear();
331     }
332 
333     /**
334      * {@inheritDoc}
335      */
336     @Override
337     public void ellipse(final double x, final double y,
338             final double radiusX, final double radiusY,
339             final double rotation, final double startAngle, final double endAngle,
340             final boolean anticlockwise) {
341         if (LOG.isDebugEnabled()) {
342             LOG.debug("[" + id_ + "] ellipse()");
343         }
344 
345         if (startAngle == endAngle) {
346             return;
347         }
348 
349         final Point2D p = transformation_.transform(new Point2D.Double(x, y), null);
350         final AffineTransform transformation = new AffineTransform();
351         transformation.rotate(rotation, p.getX(), p.getY());
352 
353         double startAngleDegree = Math.toDegrees(startAngle);
354         double endAngleDegree = Math.toDegrees(endAngle);
355 
356         double extendAngle = endAngleDegree - startAngleDegree;
357         final Arc2D arc;
358         if (Math.abs(extendAngle) >= 360) {
359             arc = new Arc2D.Double(p.getX() - radiusX, p.getY() - radiusY, radiusX * 2, radiusY * 2,
360                     0, 360, Arc2D.OPEN);
361         }
362         else {
363             startAngleDegree = reverseAngle(startAngleDegree);
364             endAngleDegree = reverseAngle(endAngleDegree);
365 
366             extendAngle = endAngleDegree - startAngleDegree;
367             if (!anticlockwise) {
368                 extendAngle = -reverseAngle(extendAngle);
369             }
370 
371             arc = new Arc2D.Double(p.getX() - radiusX, p.getY() - radiusY, radiusX * 2, radiusY * 2,
372                                             startAngleDegree, extendAngle, Arc2D.OPEN);
373         }
374 
375         // connect=true only if there is already a current point (implicit lineTo behaviour);
376         // connect=false when the subpath is new so we don't get a spurious line from (0,0)
377         // or from the moveTo seed point to the arc's own geometric start.
378         final boolean hasCurrentPoint;
379         if (subPaths_.isEmpty()) {
380             final Path2D subPath = new Path2D.Double();
381             subPaths_.add(subPath);
382             hasCurrentPoint = false;
383         }
384         else {
385             hasCurrentPoint = subPaths_.get(subPaths_.size() - 1).getCurrentPoint() != null;
386         }
387         getCurrentSubPath().append(transformation.createTransformedShape(arc), hasCurrentPoint);
388     }
389 
390     /**
391      * {@inheritDoc}
392      */
393     @Override
394     public void bezierCurveTo(final double cp1x, final double cp1y,
395             final double cp2x, final double cp2y, final double x, final double y) {
396         if (LOG.isDebugEnabled()) {
397             LOG.debug("[" + id_ + "] bezierCurveTo()");
398         }
399 
400         final Point2D cp1 = transformation_.transform(new Point2D.Double(cp1x, cp1y), null);
401         final Point2D cp2 = transformation_.transform(new Point2D.Double(cp2x, cp2y), null);
402         final Point2D p = transformation_.transform(new Point2D.Double(x, y), null);
403 
404         getCurrentSubPath(cp1.getX(), cp1.getY())
405                 .curveTo(cp1.getX(), cp1.getY(), cp2.getX(), cp2.getY(), p.getX(), p.getY());
406     }
407 
408     /**
409      * {@inheritDoc}
410      */
411     @Override
412     public void arc(final double x, final double y, final double radius, final double startAngle,
413             final double endAngle, final boolean anticlockwise) {
414         if (LOG.isDebugEnabled()) {
415             LOG.debug("[" + id_ + "] arc()");
416         }
417 
418         ellipse(x, y, radius, radius, 0, startAngle, endAngle, anticlockwise);
419     }
420 
421     private static double reverseAngle(final double degrees) {
422         return ((-degrees % 360) + 360) % 360;
423     }
424 
425     /**
426      * {@inheritDoc}
427      */
428     @Override
429     public void clearRect(final double x, final double y, final double w, final double h) {
430         if (LOG.isDebugEnabled()) {
431             LOG.debug("[" + id_ + "] clearRect(" + x + ", " + y + ", " + w + ", " + h + ")");
432         }
433 
434         final Composite savedComposite = graphics2D_.getComposite();
435         final Color savedColor = graphics2D_.getColor();
436 
437         try {
438             graphics2D_.setComposite(AlphaComposite.Clear); // force transparent clear
439             graphics2D_.fill(rectPath(x, y, w, h));
440         }
441         finally {
442             graphics2D_.setComposite(savedComposite);
443             graphics2D_.setColor(savedColor);
444         }
445     }
446 
447     /**
448      * {@inheritDoc}
449      */
450     @Override
451     public void drawImage(final org.htmlunit.platform.image.ImageData imageData,
452             final int sx, final int sy, final Integer sWidth, final Integer sHeight,
453             final int dx, final int dy, final Integer dWidth, final Integer dHeight) throws IOException {
454         if (LOG.isDebugEnabled()) {
455             LOG.debug("[" + id_ + "] drawImage(" + sx + ", " + sy + ", " + sWidth + ", " + sHeight
456                     + "," + dx + ", " + dy + ", " + dWidth + ", " + dHeight + ")");
457         }
458 
459         try {
460             final ImageReader imageReader = ((ImageIOImageData) imageData).getImageReader();
461 
462             if (imageReader.getNumImages(true) != 0) {
463                 final BufferedImage img = imageReader.read(0);
464 
465                 final AffineTransform savedTransform = graphics2D_.getTransform();
466                 try {
467                     graphics2D_.setTransform(transformation_);
468                     graphics2D_.setColor(fillColor_);
469 
470                     final int sx2;
471                     if (sWidth == null) {
472                         sx2 = sx + img.getWidth();
473                     }
474                     else {
475                         sx2 = sx + sWidth;
476                     }
477 
478                     final int sy2;
479                     if (sHeight == null) {
480                         sy2 = sy + img.getHeight();
481                     }
482                     else {
483                         sy2 = sy + sHeight;
484                     }
485 
486                     int dx1 = dx;
487                     final int dx2;
488                     if (dWidth == null) {
489                         dx2 = dx + img.getWidth();
490                     }
491                     else {
492                         if (dWidth < 0) {
493                             dx1 = dx1 + dWidth;
494                             dx2 = dx1 - dWidth;
495                         }
496                         else {
497                             dx2 = dx1 + dWidth;
498                         }
499                     }
500 
501                     int dy1 = dy;
502                     final int dy2;
503                     if (dHeight == null) {
504                         dy2 = dy + img.getHeight();
505                     }
506                     else {
507                         if (dHeight < 0) {
508                             dy1 = dy1 + dHeight;
509                             dy2 = dy1 - dHeight;
510                         }
511                         else {
512                             dy2 = dy1 + dHeight;
513                         }
514                     }
515 
516                     // the image is already completely decoded (BufferedImage), therefore the drawing is done
517                     // synchronously; no ImageObserver is needed
518                     graphics2D_.drawImage(img, dx1, dy1, dx2, dy2, sx, sy, sx2, sy2, null);
519                 }
520                 finally {
521                     graphics2D_.setTransform(savedTransform);
522                 }
523             }
524         }
525         catch (final ClassCastException e) {
526             LOG.error("[" + id_ + "] drawImage(..) failed", e);
527         }
528     }
529 
530     /**
531      * {@inheritDoc}
532      */
533     @Override
534     public String encodeToString(final String type) throws IOException {
535         String imageType = type;
536         if (imageType != null && imageType.startsWith("image/")) {
537             imageType = imageType.substring(6);
538         }
539         try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
540             ImageIO.write(image_, imageType, bos);
541 
542             final byte[] imageBytes = bos.toByteArray();
543             return new String(Base64.getEncoder().encode(imageBytes), StandardCharsets.US_ASCII);
544         }
545     }
546 
547     /**
548      * {@inheritDoc}
549      */
550     @Override
551     public void fill(final RenderingBackend.WindingRule windingRule) {
552         if (LOG.isDebugEnabled()) {
553             LOG.debug("[" + id_ + "] fill("
554                     + (windingRule == RenderingBackend.WindingRule.EVEN_ODD ? "evenOdd" : "nonZero") + ")");
555         }
556 
557         final int awtRule = (windingRule == RenderingBackend.WindingRule.EVEN_ODD)
558                 ? Path2D.WIND_EVEN_ODD
559                 : Path2D.WIND_NON_ZERO;
560 
561         // all sub paths together form one shape; filling them one by one
562         // would ignore the winding rule (e.g. a hole made of a second rect)
563         final Path2D shape = new Path2D.Double(awtRule);
564         for (final Path2D path2d : subPaths_) {
565             shape.append(path2d, false);
566         }
567 
568         graphics2D_.setColor(fillColor_);
569         graphics2D_.fill(shape);
570     }
571 
572     /**
573      * {@inheritDoc}
574      */
575     @Override
576     public void fillRect(final double x, final double y, final double w, final double h) {
577         if (LOG.isDebugEnabled()) {
578             LOG.debug("[" + id_ + "] fillRect(" + x + ", "  + y + ", "  + w + ", "  + h + ")");
579         }
580 
581         graphics2D_.setColor(fillColor_);
582         graphics2D_.fill(rectPath(x, y, w, h));
583     }
584 
585     /**
586      * {@inheritDoc}
587      */
588     @Override
589     public void fillText(final String text, final double x, final double y) {
590         if (LOG.isDebugEnabled()) {
591             LOG.debug("[" + id_ + "] fillText('" + text + "', "  + x + ", "  + y + ")");
592         }
593 
594         final AffineTransform savedTransform = graphics2D_.getTransform();
595         try {
596             graphics2D_.setTransform(transformation_);
597             graphics2D_.setColor(fillColor_);
598 
599             final FontMetrics metrics = graphics2D_.getFontMetrics();
600             final double drawX = x - textAlignOffset(metrics.getStringBounds(text, graphics2D_).getWidth());
601             final double drawY = y + textBaselineOffset(metrics);
602             graphics2D_.drawString(text, (float) drawX, (float) drawY);
603         }
604         finally {
605             graphics2D_.setTransform(savedTransform);
606         }
607     }
608 
609     /**
610      * {@inheritDoc}
611      */
612     @Override
613     public byte[] getBytes(final int width, final int height, final int sx, final int sy) {
614         if (LOG.isDebugEnabled()) {
615             LOG.debug("[" + id_ + "] getBytes(" + width + ", " + height + ", " + sx + ", " + sy + ")");
616         }
617 
618         final byte[] array = new byte[width * height * 4];
619         int index = 0;
620 
621         // Canvas ImageData order is row-major
622         for (int y = sy; y < sy + height; y++) {
623             for (int x = sx; x < sx + width; x++) {
624                 if (x < 0 || x >= image_.getWidth() || y < 0 || y >= image_.getHeight()) {
625                     array[index++] = (byte) 0;
626                     array[index++] = (byte) 0;
627                     array[index++] = (byte) 0;
628                     array[index++] = (byte) 0;
629                 }
630                 else {
631                     final int color = image_.getRGB(x, y);
632                     array[index++] = (byte) ((color >> 16) & 0xFF);  // R
633                     array[index++] = (byte) ((color >> 8) & 0xFF);   // G
634                     array[index++] = (byte) (color & 0xFF);          // B
635                     array[index++] = (byte) ((color >>> 24) & 0xFF); // A
636                 }
637             }
638         }
639 
640         return array;
641     }
642 
643     /**
644      * {@inheritDoc}
645      */
646     @Override
647     public void lineTo(final double x, final double y) {
648         if (LOG.isDebugEnabled()) {
649             LOG.debug("[" + id_ + "] lineTo(" + x + ", " + y + ")");
650         }
651 
652         final Point2D p = transformation_.transform(new Point2D.Double(x, y), null);
653         final Path2D subPath = getCurrentSubPath();
654         if (subPath.getCurrentPoint() == null) {
655             subPath.moveTo(p.getX(), p.getY());
656         }
657         else {
658             subPath.lineTo(p.getX(), p.getY());
659         }
660     }
661 
662     /**
663      * {@inheritDoc}
664      */
665     @Override
666     public void moveTo(final double x, final double y) {
667         if (LOG.isDebugEnabled()) {
668             LOG.debug("[" + id_ + "] moveTo(" + x + ", " + y + ")");
669         }
670 
671         final Point2D p = transformation_.transform(new Point2D.Double(x, y), null);
672 
673         if (!subPaths_.isEmpty()) {
674             final Path2D last = subPaths_.get(subPaths_.size() - 1);
675             if (!hasSegments(last)) {
676                 last.reset();
677                 last.moveTo(p.getX(), p.getY());
678                 return;
679             }
680         }
681 
682         final Path2D subPath = new Path2D.Double();
683         subPath.moveTo(p.getX(), p.getY());
684         subPaths_.add(subPath);
685     }
686 
687     /**
688      * {@inheritDoc}
689      */
690     @Override
691     public void putImageData(final ByteBuffer imageDataBuffer,
692             final int imageDataWidth, final int imageDataHeight,
693             final int dx, final int dy, final int dirtyX, final int dirtyY,
694             final int dirtyWidth, final int dirtyHeight) {
695 
696         if (LOG.isDebugEnabled()) {
697             LOG.debug("[" + id_ + "] putImageData()");
698         }
699         if (imageDataBuffer == null || imageDataWidth <= 0 || imageDataHeight <= 0) {
700             return;
701         }
702 
703         // Normalize dirty rect (negative width/height)
704         int sx = dirtyX;
705         int sy = dirtyY;
706         int sw = dirtyWidth;
707         int sh = dirtyHeight;
708         if (sw < 0) {
709             sx += sw;
710             sw = -sw;
711         }
712         if (sh < 0) {
713             sy += sh;
714             sh = -sh;
715         }
716         if (sw == 0 || sh == 0) {
717             return;
718         }
719 
720         // Clip dirty rect to source bounds
721         final int srcStartX = Math.max(0, sx);
722         final int srcStartY = Math.max(0, sy);
723         final int srcEndX = Math.min(imageDataWidth, sx + sw);
724         final int srcEndY = Math.min(imageDataHeight, sy + sh);
725         if (srcStartX >= srcEndX || srcStartY >= srcEndY) {
726             return;
727         }
728 
729         final int srcWidth = srcEndX - srcStartX;
730         final int srcHeight = srcEndY - srcStartY;
731 
732         final BufferedImage srcImage = new BufferedImage(srcWidth, srcHeight, BufferedImage.TYPE_INT_ARGB);
733         for (int row = 0; row < srcHeight; row++) {
734             for (int col = 0; col < srcWidth; col++) {
735                 final int byteIdx = ((srcStartY + row) * imageDataWidth + (srcStartX + col)) * 4;
736                 final int r = imageDataBuffer.get(byteIdx)     & 0xFF;
737                 final int g = imageDataBuffer.get(byteIdx + 1) & 0xFF;
738                 final int b = imageDataBuffer.get(byteIdx + 2) & 0xFF;
739                 final int a = imageDataBuffer.get(byteIdx + 3) & 0xFF;
740                 srcImage.setRGB(col, row, (a << 24) | (r << 16) | (g << 8) | b);
741             }
742         }
743 
744         final Composite savedComposite = graphics2D_.getComposite();
745         final AffineTransform savedTransform = graphics2D_.getTransform();
746         try {
747             graphics2D_.setComposite(AlphaComposite.Src);
748             graphics2D_.setTransform(new AffineTransform());
749             graphics2D_.drawImage(srcImage, dx + srcStartX, dy + srcStartY, null);
750         }
751         finally {
752             graphics2D_.setComposite(savedComposite);
753             graphics2D_.setTransform(savedTransform);
754         }
755     }
756 
757     /**
758      * {@inheritDoc}
759      */
760     @Override
761     public void quadraticCurveTo(final double cpx, final double cpy,
762                     final double x, final double y) {
763         if (LOG.isDebugEnabled()) {
764             LOG.debug("[" + id_ + "] quadraticCurveTo()");
765         }
766 
767         final Point2D cp = transformation_.transform(new Point2D.Double(cpx, cpy), null);
768         final Point2D p = transformation_.transform(new Point2D.Double(x, y), null);
769         getCurrentSubPath(cp.getX(), cp.getY()).quadTo(cp.getX(), cp.getY(), p.getX(), p.getY());
770     }
771 
772     /**
773      * {@inheritDoc}
774      */
775     @Override
776     public void rect(final double x, final double y, final double w, final double h) {
777         if (LOG.isDebugEnabled()) {
778             LOG.debug("[" + id_ + "] rect(" + x + ", "  + y + ", "  + w + ", "  + h + ")");
779         }
780 
781         final Point2D p0 = transformation_.transform(new Point2D.Double(x, y), null);
782         subPaths_.add(rectPath(x, y, w, h));
783 
784         // Spec requires a fresh subpath seeded at (x, y) after the closed rect
785         final Path2D nextPath = new Path2D.Double();
786         nextPath.moveTo(p0.getX(), p0.getY());
787         subPaths_.add(nextPath);
788     }
789 
790     /**
791      * {@inheritDoc}
792      */
793     @Override
794     public void setFillStyle(final String fillStyle) {
795         if (LOG.isDebugEnabled()) {
796             LOG.debug("[" + id_ + "] setFillStyle(" + fillStyle + ")");
797         }
798 
799         final Color color = extractColor(fillStyle);
800         if (color != null) {
801             fillColor_ = color;
802         }
803     }
804 
805     /**
806      * {@inheritDoc}
807      */
808     @Override
809     public void setStrokeStyle(final String strokeStyle) {
810         if (LOG.isDebugEnabled()) {
811             LOG.debug("[" + id_ + "] setStrokeStyle(" + strokeStyle + ")");
812         }
813 
814         final Color color = extractColor(strokeStyle);
815         if (color != null) {
816             strokeColor_ = color;
817         }
818     }
819 
820     private static Color extractColor(final String style) {
821         final String tmpStyle = style.replaceAll("\\s", "");
822 
823         Color color = toAwtColor(StringUtils.findColorRGB(tmpStyle));
824         if (color == null) {
825             color = toAwtColor(StringUtils.findColorRGBA(tmpStyle));
826         }
827         if (color == null) {
828             color = toAwtColor(StringUtils.findColorHSL(tmpStyle));
829         }
830 
831         if (color == null) {
832             if (tmpStyle.length() > 0 && tmpStyle.charAt(0) == '#') {
833                 color = toAwtColor(StringUtils.asColorHexadecimal(tmpStyle));
834             }
835             else {
836                 color = KNOWN_COLORS.get(tmpStyle.toLowerCase(Locale.ROOT));
837             }
838         }
839         return color;
840     }
841 
842     /**
843      * {@inheritDoc}
844      */
845     @Override
846     public float getLineWidth() {
847         return lineWidth_;
848     }
849 
850     /**
851      * {@inheritDoc}
852      */
853     @Override
854     public void restore() {
855         if (LOG.isDebugEnabled()) {
856             LOG.debug("[" + id_ + "] restore()");
857         }
858 
859         if (savedStates_.isEmpty()) {
860             return;
861         }
862 
863         savedStates_.pop().applyOn(this);
864     }
865 
866     /**
867      * {@inheritDoc}
868      */
869     @Override
870     public void rotate(final double angle) {
871         if (LOG.isDebugEnabled()) {
872             LOG.debug("[" + id_ + "] rotate()");
873         }
874 
875         transformation_.rotate(angle);
876     }
877 
878     /**
879      * {@inheritDoc}
880      */
881     @Override
882     public void save() {
883         if (LOG.isDebugEnabled()) {
884             LOG.debug("[" + id_ + "] save()");
885         }
886 
887         savedStates_.push(new SaveState(this));
888     }
889 
890     /**
891      * {@inheritDoc}
892      */
893     @Override
894     public void setLineWidth(final float lineWidth) {
895         if (LOG.isDebugEnabled()) {
896             LOG.debug("[" + id_ + "] setLineWidth(" + lineWidth + ")");
897         }
898 
899         lineWidth_ = lineWidth;
900     }
901 
902     /**
903      * {@inheritDoc}
904      */
905     @Override
906     public void setTransform(final double m11, final double m12,
907                     final double m21, final double m22, final double dx, final double dy) {
908         if (LOG.isDebugEnabled()) {
909             LOG.debug("[" + id_ + "] setTransform("
910                         + m11 + ", "  + m12 + ", "  + m21 + ", "  + m22 + ", "  + dx + ", "  + dy + ")");
911         }
912 
913         transformation_ = new AffineTransform(m11, m12, m21, m22, dx, dy);
914     }
915 
916     /**
917      * {@inheritDoc}
918      */
919     @Override
920     public void stroke() {
921         if (LOG.isDebugEnabled()) {
922             LOG.debug("[" + id_ + "] stroke()");
923         }
924 
925         graphics2D_.setStroke(new BasicStroke(getLineWidth(),
926                 toAwtLineCap(lineCap_), toAwtLineJoin(lineJoin_), miterLimit_));
927         graphics2D_.setColor(strokeColor_);
928 
929         for (final Path2D path2d : subPaths_) {
930             if (hasSegments(path2d)) {
931                 graphics2D_.draw(path2d);
932             }
933         }
934     }
935 
936     /**
937      * {@inheritDoc}
938      */
939     @Override
940     public void strokeRect(final double x, final double y, final double w, final double h) {
941         if (LOG.isDebugEnabled()) {
942             LOG.debug("[" + id_ + "] strokeRect(" + x + ", "  + y + ", "  + w + ", "  + h + ")");
943         }
944 
945         graphics2D_.setStroke(new BasicStroke(getLineWidth(),
946                 toAwtLineCap(lineCap_), toAwtLineJoin(lineJoin_), miterLimit_));
947         graphics2D_.setColor(strokeColor_);
948         graphics2D_.draw(rectPath(x, y, w, h));
949     }
950 
951     /**
952      * {@inheritDoc}
953      */
954     @Override
955     public void transform(final double m11, final double m12,
956                     final double m21, final double m22, final double dx, final double dy) {
957         if (LOG.isDebugEnabled()) {
958             LOG.debug("[" + id_ + "] transform()");
959         }
960 
961         transformation_.concatenate(new AffineTransform(m11, m12, m21, m22, dx, dy));
962     }
963 
964     /**
965      * {@inheritDoc}
966      */
967     @Override
968     public void translate(final double x, final double y) {
969         if (LOG.isDebugEnabled()) {
970             LOG.debug("[" + id_ + "] translate()");
971         }
972 
973         transformation_.translate(x, y);
974     }
975 
976     /**
977      * {@inheritDoc}
978      */
979     @Override
980     public void clip(final RenderingBackend.WindingRule windingRule,
981             final org.htmlunit.javascript.host.canvas.Path2D path) {
982         if (LOG.isDebugEnabled()) {
983             LOG.debug("[" + id_ + "] clip(" + windingRule + ", " + path + ")");
984         }
985 
986         final Path2D clipPath = new Path2D.Double();
987 
988         if (path == null) {
989             if (subPaths_.isEmpty()) {
990                 return;
991             }
992             for (final Path2D path2d : subPaths_) {
993                 if (hasSegments(path2d)) {
994                     clipPath.append(path2d, false);
995                 }
996             }
997         }
998         else {
999             // TODO integrate external Path2D host object once available
1000             return;
1001         }
1002 
1003         if (windingRule == WindingRule.NON_ZERO) {
1004             clipPath.setWindingRule(Path2D.WIND_NON_ZERO);
1005         }
1006         else {
1007             clipPath.setWindingRule(Path2D.WIND_EVEN_ODD);
1008         }
1009 
1010         graphics2D_.clip(clipPath);
1011     }
1012 
1013     /**
1014      * {@inheritDoc}
1015      */
1016     @Override
1017     public void closePath() {
1018         if (LOG.isDebugEnabled()) {
1019             LOG.debug("[" + id_ + "] closePath()");
1020         }
1021 
1022         if (subPaths_.isEmpty()) {
1023             return;
1024         }
1025 
1026         final Path2D current = subPaths_.get(subPaths_.size() - 1);
1027 
1028         // Extract the first point of the current subpath — this is where
1029         // the spec requires the new subpath to be seeded after closing.
1030         final double[] coords = new double[6];
1031         final PathIterator it = current.getPathIterator(null);
1032         if (it.isDone()) {
1033             return; // empty path, nothing to close
1034         }
1035         it.currentSegment(coords); // first segment is always SEG_MOVETO
1036         final double firstX = coords[0];
1037         final double firstY = coords[1];
1038 
1039         current.closePath();
1040 
1041         // Spec: "Create a new subpath with the same first point as the
1042         // previous subpath."
1043         final Path2D nextPath = new Path2D.Double();
1044         nextPath.moveTo(firstX, firstY);
1045         subPaths_.add(nextPath);
1046     }
1047 
1048     /**
1049      * {@inheritDoc}
1050      */
1051     @Override
1052     public LineJoin getLineJoin() {
1053         if (LOG.isDebugEnabled()) {
1054             LOG.debug("[" + id_ + "] getLineJoin()");
1055         }
1056         return lineJoin_;
1057     }
1058 
1059     /**
1060      * {@inheritDoc}
1061      */
1062     @Override
1063     public void setLineJoin(final LineJoin lineJoin) {
1064         if (LOG.isDebugEnabled()) {
1065             LOG.debug("[" + id_ + "] setLineJoin(" + lineJoin + ")");
1066         }
1067         lineJoin_ = lineJoin;
1068     }
1069 
1070     /**
1071      * {@inheritDoc}
1072      */
1073     @Override
1074     public LineCap getLineCap() {
1075         if (LOG.isDebugEnabled()) {
1076             LOG.debug("[" + id_ + "] getLineCap()");
1077         }
1078         return lineCap_;
1079     }
1080 
1081     /**
1082      * {@inheritDoc}
1083      */
1084     @Override
1085     public void setLineCap(final LineCap lineCap) {
1086         if (LOG.isDebugEnabled()) {
1087             LOG.debug("[" + id_ + "] setLineCap(" + lineCap + ")");
1088         }
1089         lineCap_ = lineCap;
1090     }
1091 
1092     /**
1093      * {@inheritDoc}
1094      */
1095     @Override
1096     public TextAlign getTextAlign() {
1097         if (LOG.isDebugEnabled()) {
1098             LOG.debug("[" + id_ + "] getTextAlign()");
1099         }
1100         return textAlign_;
1101     }
1102 
1103     /**
1104      * {@inheritDoc}
1105      */
1106     @Override
1107     public void setTextAlign(final TextAlign textAlign) {
1108         if (LOG.isDebugEnabled()) {
1109             LOG.debug("[" + id_ + "] setTextAlign(" + textAlign + ")");
1110         }
1111         textAlign_ = textAlign;
1112     }
1113 
1114     /**
1115      * {@inheritDoc}
1116      */
1117     @Override
1118     public TextBaseline getTextBaseline() {
1119         if (LOG.isDebugEnabled()) {
1120             LOG.debug("[" + id_ + "] getTextBaseline()");
1121         }
1122         return textBaseline_;
1123     }
1124 
1125     /**
1126      * {@inheritDoc}
1127      */
1128     @Override
1129     public void setTextBaseline(final TextBaseline textBaseline) {
1130         if (LOG.isDebugEnabled()) {
1131             LOG.debug("[" + id_ + "] setTextBaseline(" + textBaseline + ")");
1132         }
1133         textBaseline_ = textBaseline;
1134     }
1135 
1136     private Path2D getCurrentSubPath() {
1137         if (subPaths_.isEmpty()) {
1138             final Path2D subPath = new Path2D.Double();
1139             subPaths_.add(subPath);
1140             return subPath;
1141         }
1142         return subPaths_.get(subPaths_.size() - 1);
1143     }
1144 
1145     private Path2D getCurrentSubPath(final double x, final double y) {
1146         if (subPaths_.isEmpty()) {
1147             final Path2D subPath = new Path2D.Double();
1148             subPaths_.add(subPath);
1149             subPath.moveTo(x, y);
1150             return subPath;
1151         }
1152 
1153         final Path2D subPath = subPaths_.get(subPaths_.size() - 1);
1154         if (subPath.getCurrentPoint() == null) {
1155             subPath.moveTo(x, y);
1156         }
1157         return subPath;
1158     }
1159 
1160     private Path2D rectPath(final double x, final double y, final double w, final double h) {
1161         // Build the four corners explicitly from the raw (possibly negative) w/h
1162         // so the winding matches the Canvas spec: (x,y) → (x+w,y) → (x+w,y+h) → (x,y+h)
1163         // Do NOT use Rectangle2D.Double — it normalises negative dimensions.
1164         final Path2D rectPath = new Path2D.Double();
1165         final Point2D p0 = transformation_.transform(new Point2D.Double(x, y), null);
1166         final Point2D p1 = transformation_.transform(new Point2D.Double(x + w, y), null);
1167         final Point2D p2 = transformation_.transform(new Point2D.Double(x + w, y + h), null);
1168         final Point2D p3 = transformation_.transform(new Point2D.Double(x, y + h), null);
1169         rectPath.moveTo(p0.getX(), p0.getY());
1170         rectPath.lineTo(p1.getX(), p1.getY());
1171         rectPath.lineTo(p2.getX(), p2.getY());
1172         rectPath.lineTo(p3.getX(), p3.getY());
1173         rectPath.closePath();
1174 
1175         return rectPath;
1176     }
1177 
1178     private static boolean hasSegments(final Path2D path) {
1179         final PathIterator it = path.getPathIterator(null);
1180         while (!it.isDone()) {
1181             if (it.currentSegment(new double[6]) != PathIterator.SEG_MOVETO) {
1182                 return true;
1183             }
1184             it.next();
1185         }
1186         return false;
1187     }
1188 
1189     private static Color toAwtColor(final org.htmlunit.html.impl.Color color) {
1190         if (color == null) {
1191             return null;
1192         }
1193         return new Color(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());
1194     }
1195 
1196     private static int toAwtLineJoin(final LineJoin lineJoin) {
1197         return switch (lineJoin) {
1198             case MITER -> BasicStroke.JOIN_MITER;
1199             case ROUND -> BasicStroke.JOIN_ROUND;
1200             case BEVEL -> BasicStroke.JOIN_BEVEL;
1201         };
1202     }
1203 
1204     private static int toAwtLineCap(final LineCap lineCap) {
1205         return switch (lineCap) {
1206             case ROUND -> BasicStroke.CAP_ROUND;
1207             case SQUARE -> BasicStroke.CAP_SQUARE;
1208             case BUTT -> BasicStroke.CAP_BUTT;
1209         };
1210     }
1211 
1212     /**
1213      * Returns the horizontal offset from the x position given to fillText() to the left
1214      * side of the text (as AWT draws the text starting at the left side).
1215      * Only left-to-right text is supported; start is left and end is right.
1216      *
1217      * @param textWidth the width of the text
1218      * @return the offset to subtract from x
1219      */
1220     private double textAlignOffset(final double textWidth) {
1221         return switch (textAlign_) {
1222             case CENTER -> textWidth / 2;
1223             case RIGHT, END -> textWidth;
1224             case LEFT, START -> 0;
1225         };
1226     }
1227 
1228     /**
1229      * Returns the vertical offset from the y position given to fillText() to the alphabetic
1230      * baseline (as AWT draws the text at the alphabetic baseline).
1231      *
1232      * @param metrics the metrics of the current font
1233      * @return the offset to add to y
1234      */
1235     private double textBaselineOffset(final FontMetrics metrics) {
1236         final int ascent = metrics.getAscent();
1237         final int descent = metrics.getDescent();
1238         return switch (textBaseline_) {
1239             case TOP, HANGING -> ascent;
1240             case MIDDLE -> (ascent - descent) / 2.0;
1241             case IDEOGRAPHIC, BOTTOM -> -descent;
1242             case ALPHABETIC -> 0;
1243         };
1244     }
1245 
1246     private static final class SaveState {
1247         private final AffineTransform transformation_;
1248         private final float globalAlpha_;
1249         private final float lineWidth_;
1250         private final Color fillColor_;
1251         private final Color strokeColor_;
1252         private final Shape clip_;
1253 
1254         private final LineCap lineCap_;
1255         private final LineJoin lineJoin_;
1256         private final float miterLimit_;
1257 
1258         private final Font font_;
1259         private final TextAlign textAlign_;
1260         private final TextBaseline textBaseline_;
1261 
1262         SaveState(final AwtRenderingBackend backend) {
1263             transformation_ = new AffineTransform(backend.transformation_);
1264             globalAlpha_ = backend.globalAlpha_;
1265             lineWidth_ = backend.lineWidth_;
1266             fillColor_ = backend.fillColor_;
1267             strokeColor_ = backend.strokeColor_;
1268 
1269             lineCap_ = backend.lineCap_;
1270             lineJoin_ = backend.lineJoin_;
1271             miterLimit_ = backend.miterLimit_;
1272 
1273             // Defensive copy — getClip() can return a live mutable shape
1274             // on some Graphics2D implementations
1275             final Shape c = backend.graphics2D_.getClip();
1276             clip_ = (c == null) ? null : new Path2D.Double(c);
1277 
1278             // Font is immutable so no copy needed
1279             font_ = backend.graphics2D_.getFont();
1280             textAlign_ = backend.textAlign_;
1281             textBaseline_ = backend.textBaseline_;
1282         }
1283 
1284         void applyOn(final AwtRenderingBackend backend) {
1285             backend.transformation_ = new AffineTransform(transformation_);
1286             backend.lineWidth_ = lineWidth_;
1287             backend.fillColor_ = fillColor_;
1288             backend.strokeColor_ = strokeColor_;
1289 
1290             backend.updateGlobalAlpha(globalAlpha_);
1291 
1292             backend.lineCap_ = lineCap_;
1293             backend.lineJoin_ = lineJoin_;
1294             backend.miterLimit_ = miterLimit_;
1295 
1296             // Restore clip with another defensive copy so this SaveState
1297             // remains reusable if somehow applyOn is called more than once
1298             backend.graphics2D_.setClip((clip_ == null) ? null : new Path2D.Double(clip_));
1299 
1300             backend.graphics2D_.setFont(font_);
1301             backend.textAlign_ = textAlign_;
1302             backend.textBaseline_ = textBaseline_;
1303         }
1304     }
1305 }