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         /* Look first for ductus or an app-override renderer,
 117          * if not specified or present, then look for pisces.
 118          */
 119         final String ductusREClass = "sun.dc.DuctusRenderingEngine";
 120         final String piscesREClass = "sun.java2d.pisces.PiscesRenderingEngine";
 121         GetPropertyAction gpa =
 122             new GetPropertyAction("sun.java2d.renderer");
 123         String reClass = AccessController.doPrivileged(gpa);
 124         if (reClass == null) {
 125             reClass = ductusREClass;
 126         }
 127         try {
 128             Class<?> cls = Class.forName(reClass);
 129             reImpl = (RenderingEngine) cls.newInstance();
 130         } catch (ReflectiveOperationException ignored0) {
 131             try {
 132                 Class<?> cls = Class.forName(piscesREClass);
 133                 reImpl = (RenderingEngine) cls.newInstance();
 134             } catch (ReflectiveOperationException ignored1) {
 135             }
 136         }
 137 
 138         if (reImpl == null) {
 139             throw new InternalError("No RenderingEngine module found");
 140         }
 141 
 142         gpa = new GetPropertyAction("sun.java2d.renderer.trace");
 143         String reTrace = AccessController.doPrivileged(gpa);
 144         if (reTrace != null) {
 145             reImpl = new Tracer(reImpl);
 146         }
 147 
 148         return reImpl;
 149     }
 150 
 151     /**
 152      * Create a widened path as specified by the parameters.
 153      * <p>
 154      * The specified {@code src} {@link Shape} is widened according
 155      * to the specified attribute parameters as per the
 156      * {@link BasicStroke} specification.
 157      *
 158      * @param src the source path to be widened
 159      * @param width the width of the widened path as per {@code BasicStroke}
 160      * @param caps the end cap decorations as per {@code BasicStroke}
 161      * @param join the segment join decorations as per {@code BasicStroke}
 162      * @param miterlimit the miter limit as per {@code BasicStroke}
 163      * @param dashes the dash length array as per {@code BasicStroke}
 164      * @param dashphase the initial dash phase as per {@code BasicStroke}
 165      * @return the widened path stored in a new {@code Shape} object
 166      * @since 1.7
 167      */
 168     public abstract Shape createStrokedShape(Shape src,
 169                                              float width,
 170                                              int caps,
 171                                              int join,
 172                                              float miterlimit,
 173                                              float dashes[],
 174                                              float dashphase);
 175 
 176     /**
 177      * Sends the geometry for a widened path as specified by the parameters
 178      * to the specified consumer.
 179      * <p>
 180      * The specified {@code src} {@link Shape} is widened according
 181      * to the parameters specified by the {@link BasicStroke} object.
 182      * Adjustments are made to the path as appropriate for the
 183      * {@link VALUE_STROKE_NORMALIZE} hint if the {@code normalize}
 184      * boolean parameter is true.
 185      * Adjustments are made to the path as appropriate for the
 186      * {@link VALUE_ANTIALIAS_ON} hint if the {@code antialias}
 187      * boolean parameter is true.
 188      * <p>
 189      * The geometry of the widened path is forwarded to the indicated
 190      * {@link PathConsumer2D} object as it is calculated.
 191      *
 192      * @param src the source path to be widened
 193      * @param bs the {@code BasicSroke} object specifying the
 194      *           decorations to be applied to the widened path
 195      * @param normalize indicates whether stroke normalization should
 196      *                  be applied
 197      * @param antialias indicates whether or not adjustments appropriate
 198      *                  to antialiased rendering should be applied
 199      * @param consumer the {@code PathConsumer2D} instance to forward
 200      *                 the widened geometry to
 201      * @since 1.7
 202      */
 203     public abstract void strokeTo(Shape src,
 204                                   AffineTransform at,
 205                                   BasicStroke bs,
 206                                   boolean thin,
 207                                   boolean normalize,
 208                                   boolean antialias,
 209                                   PathConsumer2D consumer);
 210 
 211     /**
 212      * Construct an antialiased tile generator for the given shape with
 213      * the given rendering attributes and store the bounds of the tile
 214      * iteration in the bbox parameter.
 215      * The {@code at} parameter specifies a transform that should affect
 216      * both the shape and the {@code BasicStroke} attributes.
 217      * The {@code clip} parameter specifies the current clip in effect
 218      * in device coordinates and can be used to prune the data for the
 219      * operation, but the renderer is not required to perform any
 220      * clipping.
 221      * If the {@code BasicStroke} parameter is null then the shape
 222      * should be filled as is, otherwise the attributes of the
 223      * {@code BasicStroke} should be used to specify a draw operation.
 224      * The {@code thin} parameter indicates whether or not the
 225      * transformed {@code BasicStroke} represents coordinates smaller
 226      * than the minimum resolution of the antialiasing rasterizer as
 227      * specified by the {@code getMinimumAAPenWidth()} method.
 228      * <p>
 229      * Upon returning, this method will fill the {@code bbox} parameter
 230      * with 4 values indicating the bounds of the iteration of the
 231      * tile generator.
 232      * The iteration order of the tiles will be as specified by the
 233      * pseudo-code:
 234      * <pre>
 235      *     for (y = bbox[1]; y < bbox[3]; y += tileheight) {
 236      *         for (x = bbox[0]; x < bbox[2]; x += tilewidth) {
 237      *         }
 238      *     }
 239      * </pre>
 240      * If there is no output to be rendered, this method may return
 241      * null.
 242      *
 243      * @param s the shape to be rendered (fill or draw)
 244      * @param at the transform to be applied to the shape and the
 245      *           stroke attributes
 246      * @param clip the current clip in effect in device coordinates
 247      * @param bs if non-null, a {@code BasicStroke} whose attributes
 248      *           should be applied to this operation
 249      * @param thin true if the transformed stroke attributes are smaller
 250      *             than the minimum dropout pen width
 251      * @param normalize true if the {@code VALUE_STROKE_NORMALIZE}
 252      *                  {@code RenderingHint} is in effect
 253      * @param bbox returns the bounds of the iteration
 254      * @return the {@code AATileGenerator} instance to be consulted
 255      *         for tile coverages, or null if there is no output to render
 256      * @since 1.7
 257      */
 258     public abstract AATileGenerator getAATileGenerator(Shape s,
 259                                                        AffineTransform at,
 260                                                        Region clip,
 261                                                        BasicStroke bs,
 262                                                        boolean thin,
 263                                                        boolean normalize,
 264                                                        int bbox[]);
 265 
 266     /**
 267      * Construct an antialiased tile generator for the given parallelogram
 268      * store the bounds of the tile iteration in the bbox parameter.
 269      * The parallelogram is specified as a starting point and 2 delta
 270      * vectors that indicate the slopes of the 2 pairs of sides of the
 271      * parallelogram.
 272      * The 4 corners of the parallelogram are defined by the 4 points:
 273      * <ul>
 274      * <li> {@code x}, {@code y}
 275      * <li> {@code x+dx1}, {@code y+dy1}
 276      * <li> {@code x+dx1+dx2}, {@code y+dy1+dy2}
 277      * <li> {@code x+dx2}, {@code y+dy2}
 278      * </ul>
 279      * The {@code lw1} and {@code lw2} parameters provide a specification
 280      * for an optionally stroked parallelogram if they are positive numbers.
 281      * The {@code lw1} parameter is the ratio of the length of the {@code dx1},
 282      * {@code dx2} delta vector to half of the line width in that same
 283      * direction.
 284      * The {@code lw2} parameter provides the same ratio for the other delta
 285      * vector.
 286      * If {@code lw1} and {@code lw2} are both greater than zero, then
 287      * the parallelogram figure is doubled by both expanding and contracting
 288      * each delta vector by its corresponding {@code lw} value.
 289      * If either (@code lw1) or {@code lw2} are also greater than 1, then
 290      * the inner (contracted) parallelogram disappears and the figure is
 291      * simply a single expanded parallelogram.
 292      * The {@code clip} parameter specifies the current clip in effect
 293      * in device coordinates and can be used to prune the data for the
 294      * operation, but the renderer is not required to perform any
 295      * clipping.
 296      * <p>
 297      * Upon returning, this method will fill the {@code bbox} parameter
 298      * with 4 values indicating the bounds of the iteration of the
 299      * tile generator.
 300      * The iteration order of the tiles will be as specified by the
 301      * pseudo-code:
 302      * <pre>
 303      *     for (y = bbox[1]; y < bbox[3]; y += tileheight) {
 304      *         for (x = bbox[0]; x < bbox[2]; x += tilewidth) {
 305      *         }
 306      *     }
 307      * </pre>
 308      * If there is no output to be rendered, this method may return
 309      * null.
 310      *
 311      * @param x the X coordinate of the first corner of the parallelogram
 312      * @param y the Y coordinate of the first corner of the parallelogram
 313      * @param dx1 the X coordinate delta of the first leg of the parallelogram
 314      * @param dy1 the Y coordinate delta of the first leg of the parallelogram
 315      * @param dx2 the X coordinate delta of the second leg of the parallelogram
 316      * @param dy2 the Y coordinate delta of the second leg of the parallelogram
 317      * @param lw1 the line width ratio for the first leg of the parallelogram
 318      * @param lw2 the line width ratio for the second leg of the parallelogram
 319      * @param clip the current clip in effect in device coordinates
 320      * @param bbox returns the bounds of the iteration
 321      * @return the {@code AATileGenerator} instance to be consulted
 322      *         for tile coverages, or null if there is no output to render
 323      * @since 1.7
 324      */
 325     public abstract AATileGenerator getAATileGenerator(double x, double y,
 326                                                        double dx1, double dy1,
 327                                                        double dx2, double dy2,
 328                                                        double lw1, double lw2,
 329                                                        Region clip,
 330                                                        int bbox[]);
 331 
 332     /**
 333      * Returns the minimum pen width that the antialiasing rasterizer
 334      * can represent without dropouts occurring.
 335      * @since 1.7
 336      */
 337     public abstract float getMinimumAAPenSize();
 338 
 339     /**
 340      * Utility method to feed a {@link PathConsumer2D} object from a
 341      * given {@link PathIterator}.
 342      * This method deals with the details of running the iterator and
 343      * feeding the consumer a segment at a time.
 344      */
 345     public static void feedConsumer(PathIterator pi, PathConsumer2D consumer) {
 346         float coords[] = new float[6];
 347         while (!pi.isDone()) {
 348             switch (pi.currentSegment(coords)) {
 349             case PathIterator.SEG_MOVETO:
 350                 consumer.moveTo(coords[0], coords[1]);
 351                 break;
 352             case PathIterator.SEG_LINETO:
 353                 consumer.lineTo(coords[0], coords[1]);
 354                 break;
 355             case PathIterator.SEG_QUADTO:
 356                 consumer.quadTo(coords[0], coords[1],
 357                                 coords[2], coords[3]);
 358                 break;
 359             case PathIterator.SEG_CUBICTO:
 360                 consumer.curveTo(coords[0], coords[1],
 361                                  coords[2], coords[3],
 362                                  coords[4], coords[5]);
 363                 break;
 364             case PathIterator.SEG_CLOSE:
 365                 consumer.closePath();
 366                 break;
 367             }
 368             pi.next();
 369         }
 370     }
 371 
 372     static class Tracer extends RenderingEngine {
 373         RenderingEngine target;
 374         String name;
 375 
 376         public Tracer(RenderingEngine target) {
 377             this.target = target;
 378             name = target.getClass().getName();
 379         }
 380 
 381         public Shape createStrokedShape(Shape src,
 382                                         float width,
 383                                         int caps,
 384                                         int join,
 385                                         float miterlimit,
 386                                         float dashes[],
 387                                         float dashphase)
 388         {
 389             System.out.println(name+".createStrokedShape("+
 390                                src.getClass().getName()+", "+
 391                                "width = "+width+", "+
 392                                "caps = "+caps+", "+
 393                                "join = "+join+", "+
 394                                "miter = "+miterlimit+", "+
 395                                "dashes = "+dashes+", "+
 396                                "dashphase = "+dashphase+")");
 397             return target.createStrokedShape(src,
 398                                              width, caps, join, miterlimit,
 399                                              dashes, dashphase);
 400         }
 401 
 402         public void strokeTo(Shape src,
 403                              AffineTransform at,
 404                              BasicStroke bs,
 405                              boolean thin,
 406                              boolean normalize,
 407                              boolean antialias,
 408                              PathConsumer2D consumer)
 409         {
 410             System.out.println(name+".strokeTo("+
 411                                src.getClass().getName()+", "+
 412                                at+", "+
 413                                bs+", "+
 414                                (thin ? "thin" : "wide")+", "+
 415                                (normalize ? "normalized" : "pure")+", "+
 416                                (antialias ? "AA" : "non-AA")+", "+
 417                                consumer.getClass().getName()+")");
 418             target.strokeTo(src, at, bs, thin, normalize, antialias, consumer);
 419         }
 420 
 421         public float getMinimumAAPenSize() {
 422             System.out.println(name+".getMinimumAAPenSize()");
 423             return target.getMinimumAAPenSize();
 424         }
 425 
 426         public AATileGenerator getAATileGenerator(Shape s,
 427                                                   AffineTransform at,
 428                                                   Region clip,
 429                                                   BasicStroke bs,
 430                                                   boolean thin,
 431                                                   boolean normalize,
 432                                                   int bbox[])
 433         {
 434             System.out.println(name+".getAATileGenerator("+
 435                                s.getClass().getName()+", "+
 436                                at+", "+
 437                                clip+", "+
 438                                bs+", "+
 439                                (thin ? "thin" : "wide")+", "+
 440                                (normalize ? "normalized" : "pure")+")");
 441             return target.getAATileGenerator(s, at, clip,
 442                                              bs, thin, normalize,
 443                                              bbox);
 444         }
 445         public AATileGenerator getAATileGenerator(double x, double y,
 446                                                   double dx1, double dy1,
 447                                                   double dx2, double dy2,
 448                                                   double lw1, double lw2,
 449                                                   Region clip,
 450                                                   int bbox[])
 451         {
 452             System.out.println(name+".getAATileGenerator("+
 453                                x+", "+y+", "+
 454                                dx1+", "+dy1+", "+
 455                                dx2+", "+dy2+", "+
 456                                lw1+", "+lw2+", "+
 457                                clip+")");
 458             return target.getAATileGenerator(x, y,
 459                                              dx1, dy1,
 460                                              dx2, dy2,
 461                                              lw1, lw2,
 462                                              clip, bbox);
 463         }
 464     }
 465 }