1 /*
   2  * Copyright (c) 1997, 2010, 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 /*
  27  * @author Charlton Innovations, Inc.
  28  */
  29 
  30 package sun.java2d.loops;
  31 
  32 import java.awt.image.BufferedImage;
  33 import java.awt.AlphaComposite;
  34 import java.awt.Rectangle;
  35 import sun.awt.image.BufImgSurfaceData;
  36 import sun.java2d.SurfaceData;
  37 import sun.java2d.pipe.Region;
  38 import java.lang.reflect.Field;
  39 import java.util.StringTokenizer;
  40 import java.util.Iterator;
  41 import java.util.HashMap;
  42 import java.util.Map;
  43 import java.io.PrintStream;
  44 import java.io.OutputStream;
  45 import java.io.FileOutputStream;
  46 import java.io.FileNotFoundException;
  47 import java.security.AccessController;
  48 import java.security.PrivilegedAction;
  49 import sun.security.action.GetPropertyAction;
  50 
  51 /**
  52  * defines interface for primitives which can be placed into
  53  * the graphic component manager framework
  54  */
  55 public abstract class GraphicsPrimitive {
  56 
  57     protected static interface GeneralBinaryOp {
  58         /**
  59          * This method allows the setupGeneralBinaryOp method to set
  60          * the converters into the General version of the Primitive.
  61          */
  62         public void setPrimitives(Blit srcconverter,
  63                                   Blit dstconverter,
  64                                   GraphicsPrimitive genericop,
  65                                   Blit resconverter);
  66 
  67         /**
  68          * These 4 methods are implemented automatically for any
  69          * GraphicsPrimitive.  They are used by setupGeneralBinaryOp
  70          * to retrieve the information needed to find the right
  71          * converter primitives.
  72          */
  73         public SurfaceType getSourceType();
  74         public CompositeType getCompositeType();
  75         public SurfaceType getDestType();
  76         public String getSignature();
  77         public int getPrimTypeID();
  78     }
  79 
  80     protected static interface GeneralUnaryOp {
  81         /**
  82          * This method allows the setupGeneralUnaryOp method to set
  83          * the converters into the General version of the Primitive.
  84          */
  85         public void setPrimitives(Blit dstconverter,
  86                                   GraphicsPrimitive genericop,
  87                                   Blit resconverter);
  88 
  89         /**
  90          * These 3 methods are implemented automatically for any
  91          * GraphicsPrimitive.  They are used by setupGeneralUnaryOp
  92          * to retrieve the information needed to find the right
  93          * converter primitives.
  94          */
  95         public CompositeType getCompositeType();
  96         public SurfaceType getDestType();
  97         public String getSignature();
  98         public int getPrimTypeID();
  99     }
 100 
 101     /**
 102     *  INSTANCE DATA MEMBERS DESCRIBING CHARACTERISTICS OF THIS PRIMITIVE
 103     **/
 104 
 105     // Making these be instance data members (instead of virtual methods
 106     // overridden by subclasses) is actually cheaper, since each class
 107     // is a singleton.  As instance data members with final accessors,
 108     // accesses can be inlined.
 109     private String methodSignature;
 110     private int uniqueID;
 111     private static int unusedPrimID = 1;
 112 
 113     private SurfaceType sourceType;
 114     private CompositeType compositeType;
 115     private SurfaceType destType;
 116 
 117     private long pNativePrim;   // Native blit loop info
 118 
 119     public synchronized static final int makePrimTypeID() {
 120         if (unusedPrimID > 255) {
 121             throw new InternalError("primitive id overflow");
 122         }
 123         return unusedPrimID++;
 124     }
 125 
 126     public synchronized static final int makeUniqueID(int primTypeID,
 127                                                       SurfaceType src,
 128                                                       CompositeType cmp,
 129                                                       SurfaceType dst)
 130     {
 131         return (primTypeID << 24) |
 132             (dst.getUniqueID() << 16) |
 133             (cmp.getUniqueID() << 8)  |
 134             (src.getUniqueID());
 135     }
 136 
 137     /**
 138      * Create a new GraphicsPrimitive with all of the required
 139      * descriptive information.
 140      */
 141     protected GraphicsPrimitive(String methodSignature,
 142                                 int primTypeID,
 143                                 SurfaceType sourceType,
 144                                 CompositeType compositeType,
 145                                 SurfaceType destType)
 146     {
 147         this.methodSignature = methodSignature;
 148         this.sourceType = sourceType;
 149         this.compositeType = compositeType;
 150         this.destType = destType;
 151 
 152         if(sourceType == null || compositeType == null || destType == null) {
 153             this.uniqueID = primTypeID << 24;
 154         } else {
 155             this.uniqueID = GraphicsPrimitive.makeUniqueID(primTypeID,
 156                                                            sourceType,
 157                                                            compositeType,
 158                                                            destType);
 159         }
 160     }
 161 
 162     /**
 163      * Create a new GraphicsPrimitive for native invocation
 164      * with all of the required descriptive information.
 165      */
 166     protected GraphicsPrimitive(long pNativePrim,
 167                                 String methodSignature,
 168                                 int primTypeID,
 169                                 SurfaceType sourceType,
 170                                 CompositeType compositeType,
 171                                 SurfaceType destType)
 172     {
 173         this.pNativePrim = pNativePrim;
 174         this.methodSignature = methodSignature;
 175         this.sourceType = sourceType;
 176         this.compositeType = compositeType;
 177         this.destType = destType;
 178 
 179         if(sourceType == null || compositeType == null || destType == null) {
 180             this.uniqueID = primTypeID << 24;
 181         } else {
 182             this.uniqueID = GraphicsPrimitive.makeUniqueID(primTypeID,
 183                                                            sourceType,
 184                                                            compositeType,
 185                                                            destType);
 186         }
 187     }
 188 
 189     /**
 190     *   METHODS TO DESCRIBE THE SURFACES PRIMITIVES
 191     *   CAN OPERATE ON AND THE FUNCTIONALITY THEY IMPLEMENT
 192     **/
 193 
 194     /**
 195      * Gets instance ID of this graphics primitive.
 196      *
 197      * Instance ID is comprised of four distinct ids (ORed together)
 198      * that uniquely identify each instance of a GraphicsPrimitive
 199      * object. The four ids making up instance ID are:
 200      * 1. primitive id - identifier shared by all primitives of the
 201      * same type (eg. all Blits have the same primitive id)
 202      * 2. sourcetype id - identifies source surface type
 203      * 3. desttype id - identifies destination surface type
 204      * 4. compositetype id - identifies composite used
 205      *
 206      * @return instance ID
 207      */
 208     public final int getUniqueID() {
 209         return uniqueID;
 210     }
 211 
 212     /**
 213      */
 214     public final String getSignature() {
 215         return methodSignature;
 216     }
 217 
 218     /**
 219      * Gets unique id for this GraphicsPrimitive type.
 220      *
 221      * This id is used to identify the TYPE of primitive (Blit vs. BlitBg)
 222      * as opposed to INSTANCE of primitive.
 223      *
 224      * @return primitive ID
 225      */
 226     public final int getPrimTypeID() {
 227         return uniqueID >>> 24;
 228     }
 229 
 230     /**
 231      */
 232     public final long getNativePrim() {
 233         return pNativePrim;
 234     }
 235 
 236     /**
 237      */
 238     public final SurfaceType getSourceType() {
 239         return sourceType;
 240     }
 241 
 242     /**
 243      */
 244     public final CompositeType getCompositeType() {
 245         return compositeType;
 246     }
 247 
 248     /**
 249      */
 250     public final SurfaceType getDestType() {
 251         return destType;
 252     }
 253 
 254     /**
 255      * Return true if this primitive can be used for the given signature
 256      * surfaces, and composite.
 257      *
 258      * @param signature The signature of the given operation.  Must be
 259      *          == (not just .equals) the signature string given by the
 260      *          abstract class that declares the operation.
 261      * @param srctype The surface type for the source of the operation
 262      * @param comptype The composite type for the operation
 263      * @param dsttype The surface type for the destination of the operation
 264      */
 265     public final boolean satisfies(String signature,
 266                                    SurfaceType srctype,
 267                                    CompositeType comptype,
 268                                    SurfaceType dsttype)
 269     {
 270         if (signature != methodSignature) {
 271             return false;
 272         }
 273         while (true) {
 274             if (srctype == null) {
 275                 return false;
 276             }
 277             if (srctype.equals(sourceType)) {
 278                 break;
 279             }
 280             srctype = srctype.getSuperType();
 281         }
 282         while (true) {
 283             if (comptype == null) {
 284                 return false;
 285             }
 286             if (comptype.equals(compositeType)) {
 287                 break;
 288             }
 289             comptype = comptype.getSuperType();
 290         }
 291         while (true) {
 292             if (dsttype == null) {
 293                 return false;
 294             }
 295             if (dsttype.equals(destType)) {
 296                 break;
 297             }
 298             dsttype = dsttype.getSuperType();
 299         }
 300         return true;
 301     }
 302 
 303     //
 304     // A version of satisfies used for regression testing
 305     //
 306     final boolean satisfiesSameAs(GraphicsPrimitive other) {
 307         return (methodSignature == other.methodSignature &&
 308                 sourceType.equals(other.sourceType) &&
 309                 compositeType.equals(other.compositeType) &&
 310                 destType.equals(other.destType));
 311     }
 312 
 313     public abstract GraphicsPrimitive makePrimitive(SurfaceType srctype,
 314                                                     CompositeType comptype,
 315                                                     SurfaceType dsttype);
 316 
 317     public abstract GraphicsPrimitive traceWrap();
 318 
 319     @SuppressWarnings("rawtypes")
 320     static HashMap traceMap;
 321 
 322     public static int traceflags;
 323     public static String tracefile;
 324     public static PrintStream traceout;
 325 
 326     public static final int TRACELOG = 1;
 327     public static final int TRACETIMESTAMP = 2;
 328     public static final int TRACECOUNTS = 4;
 329 
 330     static {
 331         GetPropertyAction gpa = new GetPropertyAction("sun.java2d.trace");
 332         String trace = AccessController.doPrivileged(gpa);
 333         if (trace != null) {
 334             boolean verbose = false;
 335             int traceflags = 0;
 336             StringTokenizer st = new StringTokenizer(trace, ",");
 337             while (st.hasMoreTokens()) {
 338                 String tok = st.nextToken();
 339                 if (tok.equalsIgnoreCase("count")) {
 340                     traceflags |= GraphicsPrimitive.TRACECOUNTS;
 341                 } else if (tok.equalsIgnoreCase("log")) {
 342                     traceflags |= GraphicsPrimitive.TRACELOG;
 343                 } else if (tok.equalsIgnoreCase("timestamp")) {
 344                     traceflags |= GraphicsPrimitive.TRACETIMESTAMP;
 345                 } else if (tok.equalsIgnoreCase("verbose")) {
 346                     verbose = true;
 347                 } else if (tok.regionMatches(true, 0, "out:", 0, 4)) {
 348                     tracefile = tok.substring(4);
 349                 } else {
 350                     if (!tok.equalsIgnoreCase("help")) {
 351                         System.err.println("unrecognized token: "+tok);
 352                     }
 353                     System.err.println("usage: -Dsun.java2d.trace="+
 354                                        "[log[,timestamp]],[count],"+
 355                                        "[out:<filename>],[help],[verbose]");
 356                 }
 357             }
 358             if (verbose) {
 359                 System.err.print("GraphicsPrimitive logging ");
 360                 if ((traceflags & GraphicsPrimitive.TRACELOG) != 0) {
 361                     System.err.println("enabled");
 362                     System.err.print("GraphicsPrimitive timetamps ");
 363                     if ((traceflags & GraphicsPrimitive.TRACETIMESTAMP) != 0) {
 364                         System.err.println("enabled");
 365                     } else {
 366                         System.err.println("disabled");
 367                     }
 368                 } else {
 369                     System.err.println("[and timestamps] disabled");
 370                 }
 371                 System.err.print("GraphicsPrimitive invocation counts ");
 372                 if ((traceflags & GraphicsPrimitive.TRACECOUNTS) != 0) {
 373                     System.err.println("enabled");
 374                 } else {
 375                     System.err.println("disabled");
 376                 }
 377                 System.err.print("GraphicsPrimitive trace output to ");
 378                 if (tracefile == null) {
 379                     System.err.println("System.err");
 380                 } else {
 381                     System.err.println("file '"+tracefile+"'");
 382                 }
 383             }
 384             GraphicsPrimitive.traceflags = traceflags;
 385         }
 386     }
 387 
 388     public static boolean tracingEnabled() {
 389         return (traceflags != 0);
 390     }
 391 
 392     private static PrintStream getTraceOutputFile() {
 393         if (traceout == null) {
 394             if (tracefile != null) {
 395                 FileOutputStream o = AccessController.doPrivileged(
 396                     new PrivilegedAction<FileOutputStream>() {
 397                         public FileOutputStream run() {
 398                             try {
 399                                 return new FileOutputStream(tracefile);
 400                             } catch (FileNotFoundException e) {
 401                                 return null;
 402                             }
 403                         }
 404                     });
 405                 if (o != null) {
 406                     traceout = new PrintStream(o);
 407                 } else {
 408                     traceout = System.err;
 409                 }
 410             } else {
 411                 traceout = System.err;
 412             }
 413         }
 414         return traceout;
 415     }
 416 
 417     public static class TraceReporter extends Thread {
 418         public static void setShutdownHook() {
 419             AccessController.doPrivileged(new PrivilegedAction<Void>() {
 420                 public Void run() {
 421                     TraceReporter t = new TraceReporter();
 422                     t.setContextClassLoader(null);
 423                     Runtime.getRuntime().addShutdownHook(t);
 424                     return null;
 425                 }
 426             });
 427         }
 428 
 429         public void run() {
 430             PrintStream ps = getTraceOutputFile();
 431             @SuppressWarnings("rawtypes")
 432             Iterator iterator = traceMap.entrySet().iterator();
 433             long total = 0;
 434             int numprims = 0;
 435             while (iterator.hasNext()) {
 436                 @SuppressWarnings("rawtypes")
 437                 Map.Entry me = (Map.Entry) iterator.next();
 438                 Object prim = me.getKey();
 439                 int[] count = (int[]) me.getValue();
 440                 if (count[0] == 1) {
 441                     ps.print("1 call to ");
 442                 } else {
 443                     ps.print(count[0]+" calls to ");
 444                 }
 445                 ps.println(prim);
 446                 numprims++;
 447                 total += count[0];
 448             }
 449             if (numprims == 0) {
 450                 ps.println("No graphics primitives executed");
 451             } else if (numprims > 1) {
 452                 ps.println(total+" total calls to "+
 453                            numprims+" different primitives");
 454             }
 455         }
 456     }
 457 
 458     @SuppressWarnings({ "rawtypes", "unchecked" })
 459     public synchronized static void tracePrimitive(Object prim) {
 460         if ((traceflags & TRACECOUNTS) != 0) {
 461             if (traceMap == null) {
 462                 traceMap = new HashMap();
 463                 TraceReporter.setShutdownHook();
 464             }
 465             Object o = traceMap.get(prim);
 466             if (o == null) {
 467                 o = new int[1];
 468                 traceMap.put(prim, o);
 469             }
 470             ((int[]) o)[0]++;
 471         }
 472         if ((traceflags & TRACELOG) != 0) {
 473             PrintStream ps = getTraceOutputFile();
 474             if ((traceflags & TRACETIMESTAMP) != 0) {
 475                 ps.print(System.currentTimeMillis()+": ");
 476             }
 477             ps.println(prim);
 478         }
 479     }
 480 
 481     protected void setupGeneralBinaryOp(GeneralBinaryOp gbo) {
 482         int primID = gbo.getPrimTypeID();
 483         String methodSignature = gbo.getSignature();
 484         SurfaceType srctype = gbo.getSourceType();
 485         CompositeType comptype = gbo.getCompositeType();
 486         SurfaceType dsttype = gbo.getDestType();
 487         Blit convertsrc, convertdst, convertres;
 488         GraphicsPrimitive performop;
 489 
 490         convertsrc = createConverter(srctype, SurfaceType.IntArgb);
 491         performop = GraphicsPrimitiveMgr.locatePrim(primID,
 492                                                     SurfaceType.IntArgb,
 493                                                     comptype, dsttype);
 494         if (performop != null) {
 495             convertdst = null;
 496             convertres = null;
 497         } else {
 498             performop = getGeneralOp(primID, comptype);
 499             if (performop == null) {
 500                 throw new InternalError("Cannot construct general op for "+
 501                                         methodSignature+" "+comptype);
 502             }
 503             convertdst = createConverter(dsttype, SurfaceType.IntArgb);
 504             convertres = createConverter(SurfaceType.IntArgb, dsttype);
 505         }
 506 
 507         gbo.setPrimitives(convertsrc, convertdst, performop, convertres);
 508     }
 509 
 510     protected void setupGeneralUnaryOp(GeneralUnaryOp guo) {
 511         int primID = guo.getPrimTypeID();
 512         String methodSignature = guo.getSignature();
 513         CompositeType comptype = guo.getCompositeType();
 514         SurfaceType dsttype = guo.getDestType();
 515 
 516         Blit convertdst = createConverter(dsttype, SurfaceType.IntArgb);
 517         GraphicsPrimitive performop = getGeneralOp(primID, comptype);
 518         Blit convertres = createConverter(SurfaceType.IntArgb, dsttype);
 519         if (convertdst == null || performop == null || convertres == null) {
 520             throw new InternalError("Cannot construct binary op for "+
 521                                     comptype+" "+dsttype);
 522         }
 523 
 524         guo.setPrimitives(convertdst, performop, convertres);
 525     }
 526 
 527     protected static Blit createConverter(SurfaceType srctype,
 528                                           SurfaceType dsttype)
 529     {
 530         if (srctype.equals(dsttype)) {
 531             return null;
 532         }
 533         Blit cv = Blit.getFromCache(srctype, CompositeType.SrcNoEa, dsttype);
 534         if (cv == null) {
 535             throw new InternalError("Cannot construct converter for "+
 536                                     srctype+"=>"+dsttype);
 537         }
 538         return cv;
 539     }
 540 
 541     protected static SurfaceData convertFrom(Blit ob, SurfaceData srcData,
 542                                              int srcX, int srcY, int w, int h,
 543                                              SurfaceData dstData)
 544     {
 545         return convertFrom(ob, srcData,
 546                            srcX, srcY, w, h, dstData,
 547                            BufferedImage.TYPE_INT_ARGB);
 548     }
 549 
 550     protected static SurfaceData convertFrom(Blit ob, SurfaceData srcData,
 551                                              int srcX, int srcY, int w, int h,
 552                                              SurfaceData dstData, int type)
 553     {
 554         if (dstData != null) {
 555             Rectangle r = dstData.getBounds();
 556             if (w > r.width || h > r.height) {
 557                 dstData = null;
 558             }
 559         }
 560         if (dstData == null) {
 561             BufferedImage dstBI = new BufferedImage(w, h, type);
 562             dstData = BufImgSurfaceData.createData(dstBI);
 563         }
 564         ob.Blit(srcData, dstData, AlphaComposite.Src, null,
 565                 srcX, srcY, 0, 0, w, h);
 566         return dstData;
 567     }
 568 
 569     protected static void convertTo(Blit ob,
 570                                     SurfaceData srcImg, SurfaceData dstImg,
 571                                     Region clip,
 572                                     int dstX, int dstY, int w, int h)
 573     {
 574         if (ob != null) {
 575             ob.Blit(srcImg, dstImg, AlphaComposite.Src, clip,
 576                     0, 0, dstX, dstY, w, h);
 577         }
 578     }
 579 
 580     protected static GraphicsPrimitive getGeneralOp(int primID,
 581                                                     CompositeType comptype)
 582     {
 583         return GraphicsPrimitiveMgr.locatePrim(primID,
 584                                                SurfaceType.IntArgb,
 585                                                comptype,
 586                                                SurfaceType.IntArgb);
 587     }
 588 
 589     public static String simplename(Field[] fields, Object o) {
 590         for (int i = 0; i < fields.length; i++) {
 591             Field f = fields[i];
 592             try {
 593                 if (o == f.get(null)) {
 594                     return f.getName();
 595                 }
 596             } catch (Exception e) {
 597             }
 598         }
 599         return "\""+o.toString()+"\"";
 600     }
 601 
 602     public static String simplename(SurfaceType st) {
 603         return simplename(SurfaceType.class.getDeclaredFields(), st);
 604     }
 605 
 606     public static String simplename(CompositeType ct) {
 607         return simplename(CompositeType.class.getDeclaredFields(), ct);
 608     }
 609 
 610     private String cachedname;
 611 
 612     public String toString() {
 613         if (cachedname == null) {
 614             String sig = methodSignature;
 615             int index = sig.indexOf('(');
 616             if (index >= 0) {
 617                 sig = sig.substring(0, index);
 618             }
 619             cachedname = (getClass().getName()+"::"+
 620                           sig+"("+
 621                           simplename(sourceType)+", "+
 622                           simplename(compositeType)+", "+
 623                           simplename(destType)+")");
 624         }
 625         return cachedname;
 626     }
 627 }