1 /*
   2  * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package sun.java2d.pipe;
  27 
  28 import java.awt.Shape;
  29 import java.awt.BasicStroke;
  30 import java.awt.geom.PathIterator;
  31 import java.awt.geom.AffineTransform;
  32 
  33 import java.security.PrivilegedAction;
  34 import java.security.AccessController;
  35 import sun.security.action.GetPropertyAction;
  36 
  37 import sun.awt.geom.PathConsumer2D;
  38 
  39 /**
  40  * This class abstracts a number of features for which the Java 2D
  41  * implementation relies on proprietary licensed software libraries.
  42  * Access to those features is now achieved by retrieving the singleton
  43  * instance of this class and calling the appropriate methods on it.
  44  * The 3 primary features abstracted here include:
  45  * <dl>
  46  * <dt>Shape createStrokedShape(Shape, [BasicStroke attributes]);
  47  * <dd>This method implements the functionality of the method of the
  48  * same name on the {@link BasicStroke} class.
  49  * <dt>void strokeTo(Shape, [rendering parameters], PathConsumer2D);
  50  * <dd>This method performs widening of the source path on the fly
  51  * and sends the results to the given {@link PathConsumer2D} object.
  52  * This procedure avoids having to create an intermediate Shape
  53  * object to hold the results of the {@code createStrokedShape} method.
  54  * The main user of this method is the Java 2D non-antialiasing renderer.
  55  * <dt>AATileGenerator getAATileGenerator(Shape, [rendering parameters]);
  56  * <dd>This method returns an object which can iterate over the
  57  * specified bounding box and produce tiles of coverage values for
  58  * antialiased rendering.  The details of the operation of the
  59  * {@link AATileGenerator} object are explained in its class comments.
  60  * </dl>
  61  * Additionally, the following informational method supplies important
  62  * data about the implementation.
  63  * <dl>
  64  * <dt>float getMinimumAAPenSize()
  65  * <dd>This method provides information on how small the BasicStroke
  66  * line width can get before dropouts occur.  Rendering with a BasicStroke
  67  * is defined to never allow the line to have breaks, gaps, or dropouts
  68  * even if the width is set to 0.0f, so this information allows the
  69  * {@link SunGraphics2D} class to detect the "thin line" case and set
  70  * the rendering attributes accordingly.
  71  * </dl>
  72  * At startup the runtime will load a single instance of this class.
  73  * It searches the classpath for a registered provider of this API
  74  * and returns either the last one it finds, or the instance whose
  75  * class name matches the value supplied in the System property
  76  * {@code sun.java2d.renderer}.
  77  * Additionally, a runtime System property flag can be set to trace
  78  * all calls to methods on the {@code RenderingEngine} in use by
  79  * setting the sun.java2d.renderer.trace property to any non-null value.
  80  * <p>
  81  * Parts of the system that need to use any of the above features should
  82  * call {@code RenderingEngine.getInstance()} to obtain the properly
  83  * registered (and possibly trace-enabled) version of the RenderingEngine.
  84  */
  85 public abstract class RenderingEngine {
  86     private static RenderingEngine reImpl;
  87 
  88     /**
  89      * Returns an instance of {@code RenderingEngine} as determined
  90      * by the installation environment and runtime flags.
  91      * <p>
  92      * A specific instance of the {@code RenderingEngine} can be
  93      * chosen by specifying the runtime flag:
  94      * <pre>
  95      *     java -Dsun.java2d.renderer=&lt;classname&gt;
  96      * </pre>
  97      *
  98      * If no specific {@code RenderingEngine} is specified on the command
  99      * or Ductus renderer is specified, it will first attempt loading the
 100      * sun.dc.DuctusRenderingEngine class using Class.forName, if that
 101      * is not found, then it will look for Pisces.
 102      * <p>
 103      * Runtime tracing of the actions of the {@code RenderingEngine}
 104      * can be enabled by specifying the runtime flag:
 105      * <pre>
 106      *     java -Dsun.java2d.renderer.trace=&lt;any string&gt;
 107      * </pre>
 108      * @return an instance of {@code RenderingEngine}
 109      * @since 1.7
 110      */
 111     public static synchronized RenderingEngine getInstance() {
 112         if (reImpl != null) {
 113             return reImpl;
 114         }
 115 
 116         reImpl =
 117             AccessController.doPrivileged(new PrivilegedAction<RenderingEngine>() {
 118                 public RenderingEngine run() {
 119                     /* Look first for ductus or an app-override renderer,
 120                      * if not specified or present, then look for pisces.
 121                      */
 122                     final String ductusREClass = "sun.dc.DuctusRenderingEngine";
 123                     final String piscesREClass = "sun.java2d.pisces.PiscesRenderingEngine";
 124                     String reClass = System.getProperty("sun.java2d.renderer");
 125                     if (reClass == null) {
 126                         reClass = ductusREClass;
 127                     }
 128                     try {
 129                         Class<?> cls = Class.forName(reClass);
 130                         return (RenderingEngine) cls.newInstance();
 131                     } catch (ReflectiveOperationException ignored) {
 132                         // not found
 133                     }
 134                     try {
 135                         Class<?> cls = Class.forName(piscesREClass);
 136                         return (RenderingEngine) cls.newInstance();
 137                     } catch (ReflectiveOperationException ignored) {
 138                         // not found
 139                     }
 140 
 141                     return null;
 142                 }
 143             });
 144 
 145         if (reImpl == null) {
 146             throw new InternalError("No RenderingEngine module found");
 147         }
 148 
 149         GetPropertyAction gpa =
 150             new GetPropertyAction("sun.java2d.renderer.trace");
 151         String reTrace = AccessController.doPrivileged(gpa);
 152         if (reTrace != null) {
 153             reImpl = new Tracer(reImpl);
 154         }
 155 
 156         return reImpl;
 157     }
 158 
 159     /**
 160      * Create a widened path as specified by the parameters.
 161      * <p>
 162      * The specified {@code src} {@link Shape} is widened according
 163      * to the specified attribute parameters as per the
 164      * {@link BasicStroke} specification.
 165      *
 166      * @param src the source path to be widened
 167      * @param width the width of the widened path as per {@code BasicStroke}
 168      * @param caps the end cap decorations as per {@code BasicStroke}
 169      * @param join the segment join decorations as per {@code BasicStroke}
 170      * @param miterlimit the miter limit as per {@code BasicStroke}
 171      * @param dashes the dash length array as per {@code BasicStroke}
 172      * @param dashphase the initial dash phase as per {@code BasicStroke}
 173      * @return the widened path stored in a new {@code Shape} object
 174      * @since 1.7
 175      */
 176     public abstract Shape createStrokedShape(Shape src,
 177                                              float width,
 178                                              int caps,
 179                                              int join,
 180                                              float miterlimit,
 181                                              float dashes[],
 182                                              float dashphase);
 183 
 184     /**
 185      * Sends the geometry for a widened path as specified by the parameters
 186      * to the specified consumer.
 187      * <p>
 188      * The specified {@code src} {@link Shape} is widened according
 189      * to the parameters specified by the {@link BasicStroke} object.
 190      * Adjustments are made to the path as appropriate for the
 191      * {@link VALUE_STROKE_NORMALIZE} hint if the {@code normalize}
 192      * boolean parameter is true.
 193      * Adjustments are made to the path as appropriate for the
 194      * {@link VALUE_ANTIALIAS_ON} hint if the {@code antialias}
 195      * boolean parameter is true.
 196      * <p>
 197      * The geometry of the widened path is forwarded to the indicated
 198      * {@link PathConsumer2D} object as it is calculated.
 199      *
 200      * @param src the source path to be widened
 201      * @param bs the {@code BasicSroke} object specifying the
 202      *           decorations to be applied to the widened path
 203      * @param normalize indicates whether stroke normalization should
 204      *                  be applied
 205      * @param antialias indicates whether or not adjustments appropriate
 206      *                  to antialiased rendering should be applied
 207      * @param consumer the {@code PathConsumer2D} instance to forward
 208      *                 the widened geometry to
 209      * @since 1.7
 210      */
 211     public abstract void strokeTo(Shape src,
 212                                   AffineTransform at,
 213                                   BasicStroke bs,
 214                                   boolean thin,
 215                                   boolean normalize,
 216                                   boolean antialias,
 217                                   PathConsumer2D consumer);
 218 
 219     /**
 220      * Construct an antialiased tile generator for the given shape with
 221      * the given rendering attributes and store the bounds of the tile
 222      * iteration in the bbox parameter.
 223      * The {@code at} parameter specifies a transform that should affect
 224      * both the shape and the {@code BasicStroke} attributes.
 225      * The {@code clip} parameter specifies the current clip in effect
 226      * in device coordinates and can be used to prune the data for the
 227      * operation, but the renderer is not required to perform any
 228      * clipping.
 229      * If the {@code BasicStroke} parameter is null then the shape
 230      * should be filled as is, otherwise the attributes of the
 231      * {@code BasicStroke} should be used to specify a draw operation.
 232      * The {@code thin} parameter indicates whether or not the
 233      * transformed {@code BasicStroke} represents coordinates smaller
 234      * than the minimum resolution of the antialiasing rasterizer as
 235      * specified by the {@code getMinimumAAPenWidth()} method.
 236      * <p>
 237      * Upon returning, this method will fill the {@code bbox} parameter
 238      * with 4 values indicating the bounds of the iteration of the
 239      * tile generator.
 240      * The iteration order of the tiles will be as specified by the
 241      * pseudo-code:
 242      * <pre>
 243      *     for (y = bbox[1]; y < bbox[3]; y += tileheight) {
 244      *         for (x = bbox[0]; x < bbox[2]; x += tilewidth) {
 245      *         }
 246      *     }
 247      * </pre>
 248      * If there is no output to be rendered, this method may return
 249      * null.
 250      *
 251      * @param s the shape to be rendered (fill or draw)
 252      * @param at the transform to be applied to the shape and the
 253      *           stroke attributes
 254      * @param clip the current clip in effect in device coordinates
 255      * @param bs if non-null, a {@code BasicStroke} whose attributes
 256      *           should be applied to this operation
 257      * @param thin true if the transformed stroke attributes are smaller
 258      *             than the minimum dropout pen width
 259      * @param normalize true if the {@code VALUE_STROKE_NORMALIZE}
 260      *                  {@code RenderingHint} is in effect
 261      * @param bbox returns the bounds of the iteration
 262      * @return the {@code AATileGenerator} instance to be consulted
 263      *         for tile coverages, or null if there is no output to render
 264      * @since 1.7
 265      */
 266     public abstract AATileGenerator getAATileGenerator(Shape s,
 267                                                        AffineTransform at,
 268                                                        Region clip,
 269                                                        BasicStroke bs,
 270                                                        boolean thin,
 271                                                        boolean normalize,
 272                                                        int bbox[]);
 273 
 274     /**
 275      * Construct an antialiased tile generator for the given parallelogram
 276      * store the bounds of the tile iteration in the bbox parameter.
 277      * The parallelogram is specified as a starting point and 2 delta
 278      * vectors that indicate the slopes of the 2 pairs of sides of the
 279      * parallelogram.
 280      * The 4 corners of the parallelogram are defined by the 4 points:
 281      * <ul>
 282      * <li> {@code x}, {@code y}
 283      * <li> {@code x+dx1}, {@code y+dy1}
 284      * <li> {@code x+dx1+dx2}, {@code y+dy1+dy2}
 285      * <li> {@code x+dx2}, {@code y+dy2}
 286      * </ul>
 287      * The {@code lw1} and {@code lw2} parameters provide a specification
 288      * for an optionally stroked parallelogram if they are positive numbers.
 289      * The {@code lw1} parameter is the ratio of the length of the {@code dx1},
 290      * {@code dx2} delta vector to half of the line width in that same
 291      * direction.
 292      * The {@code lw2} parameter provides the same ratio for the other delta
 293      * vector.
 294      * If {@code lw1} and {@code lw2} are both greater than zero, then
 295      * the parallelogram figure is doubled by both expanding and contracting
 296      * each delta vector by its corresponding {@code lw} value.
 297      * If either (@code lw1) or {@code lw2} are also greater than 1, then
 298      * the inner (contracted) parallelogram disappears and the figure is
 299      * simply a single expanded parallelogram.
 300      * The {@code clip} parameter specifies the current clip in effect
 301      * in device coordinates and can be used to prune the data for the
 302      * operation, but the renderer is not required to perform any
 303      * clipping.
 304      * <p>
 305      * Upon returning, this method will fill the {@code bbox} parameter
 306      * with 4 values indicating the bounds of the iteration of the
 307      * tile generator.
 308      * The iteration order of the tiles will be as specified by the
 309      * pseudo-code:
 310      * <pre>
 311      *     for (y = bbox[1]; y < bbox[3]; y += tileheight) {
 312      *         for (x = bbox[0]; x < bbox[2]; x += tilewidth) {
 313      *         }
 314      *     }
 315      * </pre>
 316      * If there is no output to be rendered, this method may return
 317      * null.
 318      *
 319      * @param x the X coordinate of the first corner of the parallelogram
 320      * @param y the Y coordinate of the first corner of the parallelogram
 321      * @param dx1 the X coordinate delta of the first leg of the parallelogram
 322      * @param dy1 the Y coordinate delta of the first leg of the parallelogram
 323      * @param dx2 the X coordinate delta of the second leg of the parallelogram
 324      * @param dy2 the Y coordinate delta of the second leg of the parallelogram
 325      * @param lw1 the line width ratio for the first leg of the parallelogram
 326      * @param lw2 the line width ratio for the second leg of the parallelogram
 327      * @param clip the current clip in effect in device coordinates
 328      * @param bbox returns the bounds of the iteration
 329      * @return the {@code AATileGenerator} instance to be consulted
 330      *         for tile coverages, or null if there is no output to render
 331      * @since 1.7
 332      */
 333     public abstract AATileGenerator getAATileGenerator(double x, double y,
 334                                                        double dx1, double dy1,
 335                                                        double dx2, double dy2,
 336                                                        double lw1, double lw2,
 337                                                        Region clip,
 338                                                        int bbox[]);
 339 
 340     /**
 341      * Returns the minimum pen width that the antialiasing rasterizer
 342      * can represent without dropouts occurring.
 343      * @since 1.7
 344      */
 345     public abstract float getMinimumAAPenSize();
 346 
 347     /**
 348      * Utility method to feed a {@link PathConsumer2D} object from a
 349      * given {@link PathIterator}.
 350      * This method deals with the details of running the iterator and
 351      * feeding the consumer a segment at a time.
 352      */
 353     public static void feedConsumer(PathIterator pi, PathConsumer2D consumer) {
 354         float coords[] = new float[6];
 355         while (!pi.isDone()) {
 356             switch (pi.currentSegment(coords)) {
 357             case PathIterator.SEG_MOVETO:
 358                 consumer.moveTo(coords[0], coords[1]);
 359                 break;
 360             case PathIterator.SEG_LINETO:
 361                 consumer.lineTo(coords[0], coords[1]);
 362                 break;
 363             case PathIterator.SEG_QUADTO:
 364                 consumer.quadTo(coords[0], coords[1],
 365                                 coords[2], coords[3]);
 366                 break;
 367             case PathIterator.SEG_CUBICTO:
 368                 consumer.curveTo(coords[0], coords[1],
 369                                  coords[2], coords[3],
 370                                  coords[4], coords[5]);
 371                 break;
 372             case PathIterator.SEG_CLOSE:
 373                 consumer.closePath();
 374                 break;
 375             }
 376             pi.next();
 377         }
 378     }
 379 
 380     static class Tracer extends RenderingEngine {
 381         RenderingEngine target;
 382         String name;
 383 
 384         public Tracer(RenderingEngine target) {
 385             this.target = target;
 386             name = target.getClass().getName();
 387         }
 388 
 389         public Shape createStrokedShape(Shape src,
 390                                         float width,
 391                                         int caps,
 392                                         int join,
 393                                         float miterlimit,
 394                                         float dashes[],
 395                                         float dashphase)
 396         {
 397             System.out.println(name+".createStrokedShape("+
 398                                src.getClass().getName()+", "+
 399                                "width = "+width+", "+
 400                                "caps = "+caps+", "+
 401                                "join = "+join+", "+
 402                                "miter = "+miterlimit+", "+
 403                                "dashes = "+dashes+", "+
 404                                "dashphase = "+dashphase+")");
 405             return target.createStrokedShape(src,
 406                                              width, caps, join, miterlimit,
 407                                              dashes, dashphase);
 408         }
 409 
 410         public void strokeTo(Shape src,
 411                              AffineTransform at,
 412                              BasicStroke bs,
 413                              boolean thin,
 414                              boolean normalize,
 415                              boolean antialias,
 416                              PathConsumer2D consumer)
 417         {
 418             System.out.println(name+".strokeTo("+
 419                                src.getClass().getName()+", "+
 420                                at+", "+
 421                                bs+", "+
 422                                (thin ? "thin" : "wide")+", "+
 423                                (normalize ? "normalized" : "pure")+", "+
 424                                (antialias ? "AA" : "non-AA")+", "+
 425                                consumer.getClass().getName()+")");
 426             target.strokeTo(src, at, bs, thin, normalize, antialias, consumer);
 427         }
 428 
 429         public float getMinimumAAPenSize() {
 430             System.out.println(name+".getMinimumAAPenSize()");
 431             return target.getMinimumAAPenSize();
 432         }
 433 
 434         public AATileGenerator getAATileGenerator(Shape s,
 435                                                   AffineTransform at,
 436                                                   Region clip,
 437                                                   BasicStroke bs,
 438                                                   boolean thin,
 439                                                   boolean normalize,
 440                                                   int bbox[])
 441         {
 442             System.out.println(name+".getAATileGenerator("+
 443                                s.getClass().getName()+", "+
 444                                at+", "+
 445                                clip+", "+
 446                                bs+", "+
 447                                (thin ? "thin" : "wide")+", "+
 448                                (normalize ? "normalized" : "pure")+")");
 449             return target.getAATileGenerator(s, at, clip,
 450                                              bs, thin, normalize,
 451                                              bbox);
 452         }
 453         public AATileGenerator getAATileGenerator(double x, double y,
 454                                                   double dx1, double dy1,
 455                                                   double dx2, double dy2,
 456                                                   double lw1, double lw2,
 457                                                   Region clip,
 458                                                   int bbox[])
 459         {
 460             System.out.println(name+".getAATileGenerator("+
 461                                x+", "+y+", "+
 462                                dx1+", "+dy1+", "+
 463                                dx2+", "+dy2+", "+
 464                                lw1+", "+lw2+", "+
 465                                clip+")");
 466             return target.getAATileGenerator(x, y,
 467                                              dx1, dy1,
 468                                              dx2, dy2,
 469                                              lw1, lw2,
 470                                              clip, bbox);
 471         }
 472     }
 473 }