1 /*
   2  * Copyright (c) 2014, 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.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 /*
  25   @test
  26   @bug 4397404 4720930
  27   @summary tests that images of all supported native image formats are transfered properly
  28   @library ../../../../lib/testlibrary
  29   @library ../../regtesthelpers/process/
  30   @build jdk.testlibrary.OSInfo ProcessResults ProcessCommunicator
  31   @author gas@sparc.spb.su area=Clipboard
  32   @run main ImageTransferTest
  33 */
  34 
  35 import test.java.awt.regtesthelpers.process.ProcessCommunicator;
  36 import test.java.awt.regtesthelpers.process.ProcessResults;
  37 import jdk.testlibrary.OSInfo;
  38 
  39 import java.awt.*;
  40 import java.awt.datatransfer.DataFlavor;
  41 import java.awt.datatransfer.SystemFlavorMap;
  42 import java.awt.datatransfer.Transferable;
  43 import java.awt.datatransfer.UnsupportedFlavorException;
  44 import java.awt.dnd.DnDConstants;
  45 import java.awt.dnd.DragSource;
  46 import java.awt.dnd.DragSourceAdapter;
  47 import java.awt.dnd.DragSourceDropEvent;
  48 import java.awt.dnd.DragSourceListener;
  49 import java.awt.dnd.DropTarget;
  50 import java.awt.dnd.DropTargetAdapter;
  51 import java.awt.dnd.DropTargetDropEvent;
  52 import java.awt.event.InputEvent;
  53 import java.awt.image.BufferedImage;
  54 import java.awt.image.MemoryImageSource;
  55 import java.util.stream.Stream;
  56 
  57 public class ImageTransferTest {
  58     public static void main(String[] arg) throws Exception {
  59         ImageDragSource ids = new ImageDragSource();
  60         ids.frame.setLocation(100, 100);
  61         ids.frame.setVisible(true);
  62         Util.sync();
  63         String classpath = System.getProperty("java.class.path");
  64         String[] args = new String[ids.formats.length + 4];
  65         args[0] = "200";
  66         args[1] = "100";
  67         args[2] = args[3] = "150";
  68 
  69         System.arraycopy(ids.formats, 0, args, 4, ids.formats.length);
  70         ProcessResults pres = ProcessCommunicator.executeChildProcess(ImageDropTarget.class, classpath, args);
  71 
  72         if (pres.getStdErr() != null && pres.getStdErr().length() > 0) {
  73             System.err.println("========= Child VM System.err ========");
  74             System.err.print(pres.getStdErr());
  75             System.err.println("======================================");
  76         }
  77 
  78         if (pres.getStdOut() != null && pres.getStdOut().length() > 0) {
  79             System.err.println("========= Child VM System.out ========");
  80             System.err.print(pres.getStdOut());
  81             System.err.println("======================================");
  82         }
  83 
  84         boolean failed = false;
  85         String passedFormats = "";
  86         String failedFormats = "";
  87 
  88         for (int i = 0; i < ids.passedArray.length; i++) {
  89             if (ids.passedArray[i]) passedFormats += ids.formats[i] + " ";
  90             else {
  91                 failed = true;
  92                 failedFormats += ids.formats[i] + " ";
  93             }
  94         }
  95 
  96         if (failed) {
  97             throw new RuntimeException("test failed: images in following " +
  98                     "native formats are not transferred properly: " + failedFormats);
  99         } else {
 100             System.err.println("images in following " +
 101                     "native formats are transferred properly: " + passedFormats);
 102         }
 103     }
 104 }
 105 
 106 
 107 class Util {
 108     private static Robot srobot = null;
 109     public static void sync() {
 110         try {
 111             if(srobot == null) {
 112                 srobot = new Robot();
 113             }
 114             srobot.waitForIdle();
 115             Thread.sleep(500);
 116         } catch (Exception e) {
 117             throw new RuntimeException(e);
 118         }
 119     }
 120 }
 121 
 122 abstract class ImageTransferer {
 123     Image image;
 124     String[] formats;
 125     int fi; // current format index
 126     Frame frame = new Frame();
 127 
 128 
 129     ImageTransferer() {
 130         image = createImage();
 131         frame.setSize(100, 100);
 132     }
 133 
 134     private static Image createImage() {
 135         int w = 100;
 136         int h = 100;
 137         int[] pix = new int[w * h];
 138 
 139         int index = 0;
 140         for (int y = 0; y < h; y++) {
 141             for (int x = 0; x < w; x++) {
 142                 int red = 127;
 143                 int green = 127;
 144                 int blue = y > h / 2 ? 127 : 0;
 145                 int alpha = 255;
 146                 if (x < w / 4 && y < h / 4) {
 147                     alpha = 0;
 148                     red = 0;
 149                 }
 150                 pix[index++] = (alpha << 24) | (red << 16) | (green << 8) | blue;
 151             }
 152         }
 153         return Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(w, h, pix, 0, w));
 154     }
 155 
 156 
 157     static String[] retrieveFormatsToTest() {
 158         SystemFlavorMap sfm = (SystemFlavorMap) SystemFlavorMap.getDefaultFlavorMap();
 159         java.util.List<String> ln = sfm.getNativesForFlavor(DataFlavor.imageFlavor);
 160         if (OSInfo.OSType.WINDOWS.equals(OSInfo.getOSType()) && !ln.contains("METAFILEPICT")) {
 161             // for test failing on JDK without this fix
 162             ln.add("METAFILEPICT");
 163         }
 164         return ln.toArray(new String[ln.size()]);
 165     }
 166 
 167     static void leaveFormat(String format) {
 168         SystemFlavorMap sfm = (SystemFlavorMap) SystemFlavorMap.getDefaultFlavorMap();
 169         sfm.setFlavorsForNative(format, new DataFlavor[]{DataFlavor.imageFlavor});
 170         sfm.setNativesForFlavor(DataFlavor.imageFlavor, new String[]{format});
 171     }
 172 
 173 
 174     boolean areImagesIdentical(Image im1, Image im2) {
 175         if (formats[fi].equals("JFIF") || formats[fi].equals("image/jpeg") ||
 176                 formats[fi].equals("GIF") || formats[fi].equals("image/gif")) {
 177             // JFIF and GIF are lossy formats
 178             return true;
 179         }
 180         int[] ib1 = getImageData(im1);
 181         int[] ib2 = getImageData(im2);
 182 
 183         if (ib1.length != ib2.length) {
 184             return false;
 185         }
 186 
 187         if (formats[fi].equals("PNG") ||
 188                 formats[fi].equals("image/png") ||
 189                 formats[fi].equals("image/x-png")) {
 190             // check alpha as well
 191             for (int i = 0; i < ib1.length; i++) {
 192                 if (ib1[i] != ib2[i]) {
 193                     System.err.println("different pixels: " +
 194                             Integer.toHexString(ib1[i]) + " " +
 195                             Integer.toHexString(ib2[i]));
 196                     return false;
 197                 }
 198             }
 199         } else {
 200             for (int i = 0; i < ib1.length; i++) {
 201                 if ((ib1[i] & 0x00FFFFFF) != (ib2[i] & 0x00FFFFFF)) {
 202                     System.err.println("different pixels: " +
 203                             Integer.toHexString(ib1[i]) + " " +
 204                             Integer.toHexString(ib2[i]));
 205                     return false;
 206                 }
 207             }
 208         }
 209         return true;
 210     }
 211 
 212     private static int[] getImageData(Image image) {
 213         int width = image.getWidth(null);
 214         int height = image.getHeight(null);
 215         BufferedImage bimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
 216         Graphics2D g2d = bimage.createGraphics();
 217         try {
 218             g2d.drawImage(image, 0, 0, width, height, null);
 219         } finally {
 220             g2d.dispose();
 221         }
 222         return bimage.getRGB(0, 0, width, height, null, 0, width);
 223     }
 224 
 225     public static int sign(int n) {
 226         return n < 0 ? -1 : n == 0 ? 0 : 1;
 227     }
 228 
 229 }
 230 
 231 
 232 class ImageDragSource extends ImageTransferer {
 233     boolean[] passedArray;
 234 
 235     ImageDragSource() {
 236         formats = retrieveFormatsToTest();
 237         passedArray = new boolean[formats.length];
 238         final DragSourceListener dsl = new DragSourceAdapter() {
 239             public void dragDropEnd(DragSourceDropEvent e) {
 240                 System.err.println("Drop was successful=" + e.getDropSuccess());
 241                 notifyTransferSuccess(e.getDropSuccess());
 242                 if (++fi < formats.length) {
 243                     leaveFormat(formats[fi]);
 244                 }
 245             }
 246         };
 247 
 248         new DragSource().createDefaultDragGestureRecognizer(frame,
 249                 DnDConstants.ACTION_COPY,
 250                 dge -> dge.startDrag(null, new ImageSelection(image), dsl));
 251         leaveFormat(formats[fi]);
 252     }
 253 
 254 
 255     void notifyTransferSuccess(boolean status) {
 256         passedArray[fi] = status;
 257     }
 258 }
 259 
 260 
 261 class ImageDropTarget extends ImageTransferer {
 262     private final Robot robot;
 263     private static Point startPoint, endPoint = new Point(250, 150);
 264 
 265     ImageDropTarget() throws AWTException {
 266         DropTargetAdapter dropTargetAdapter = new DropTargetAdapter() {
 267             @Override
 268             public void drop(DropTargetDropEvent dtde) {
 269                 checkImage(dtde);
 270                 startImageDrag();
 271             }
 272         };
 273         new DropTarget(frame, dropTargetAdapter);
 274         robot = new Robot();
 275     }
 276 
 277 
 278     void checkImage(DropTargetDropEvent dtde) {
 279         final Transferable t = dtde.getTransferable();
 280         if (t.isDataFlavorSupported(DataFlavor.imageFlavor)) {
 281             dtde.acceptDrop(DnDConstants.ACTION_COPY);
 282             Image im;
 283             try {
 284                 im = (Image) t.getTransferData(DataFlavor.imageFlavor);
 285                 System.err.println("getTransferData was successful");
 286             } catch (Exception e) {
 287                 System.err.println("Can't getTransferData: " + e);
 288                 dtde.dropComplete(false);
 289                 notifyTransferSuccess(false);
 290                 return;
 291             }
 292 
 293             if (im == null) {
 294                 System.err.println("getTransferData returned null");
 295                 dtde.dropComplete(false);
 296                 notifyTransferSuccess(false);
 297             } else if (areImagesIdentical(image, im)) {
 298                 dtde.dropComplete(true);
 299                 notifyTransferSuccess(true);
 300             } else {
 301                 System.err.println("transferred image is different from initial image");
 302                 dtde.dropComplete(false);
 303                 notifyTransferSuccess(false);
 304             }
 305 
 306         } else {
 307             System.err.println("imageFlavor is not supported by Transferable");
 308             dtde.rejectDrop();
 309             notifyTransferSuccess(false);
 310         }
 311     }
 312 
 313     void startImageDrag() {
 314         leaveFormat(formats[fi]);
 315         new Thread(() -> {
 316             try {
 317                 Thread.sleep(1000);
 318             } catch (InterruptedException e) {
 319                 e.printStackTrace();
 320                 // Exit from the child process
 321                 System.exit(1);
 322             }
 323             robot.mouseMove(startPoint.x, startPoint.y);
 324             robot.mousePress(InputEvent.BUTTON1_MASK);
 325             for (Point p = new Point(startPoint); !p.equals(endPoint);
 326                  p.translate(sign(endPoint.x - p.x), sign(endPoint.y - p.y))) {
 327                 robot.mouseMove(p.x, p.y);
 328                 try {
 329                     Thread.sleep(50);
 330                 } catch (InterruptedException e) {
 331                     e.printStackTrace();
 332                 }
 333             }
 334 
 335             robot.mouseRelease(InputEvent.BUTTON1_MASK);
 336         }).start();
 337     }
 338 
 339     void notifyTransferSuccess(boolean status) {
 340         if (status) {
 341             System.err.println("format passed: " + formats[fi]);
 342         } else {
 343             System.err.println("format failed: " + formats[fi]);
 344             System.exit(1);
 345         }
 346         if (fi < formats.length - 1) {
 347             leaveFormat(formats[++fi]);
 348         } else {
 349             new Thread(() -> {
 350                 try {
 351                     Thread.sleep(500);
 352                 } catch (InterruptedException e) {
 353                     e.printStackTrace();
 354                 }
 355                 System.exit(0);
 356             }).start();
 357         }
 358     }
 359 
 360 
 361     public static void main(String[] args) {
 362         try {
 363             ImageDropTarget idt = new ImageDropTarget();
 364 
 365             int x = Integer.parseInt(args[0]);
 366             int y = Integer.parseInt(args[1]);
 367             startPoint = new Point(Integer.parseInt(args[2]), Integer.parseInt(args[3]));
 368 
 369             idt.formats = new String[args.length - 4];
 370             System.arraycopy(args, 4, idt.formats, 0, args.length - 4);
 371             leaveFormat(idt.formats[0]);
 372 
 373             idt.frame.setLocation(x, y);
 374             idt.frame.setVisible(true);
 375             Util.sync();
 376 
 377             idt.startImageDrag();
 378         } catch (Throwable e) {
 379             e.printStackTrace();
 380             System.exit(1);
 381         }
 382     }
 383 
 384 }
 385 
 386 
 387 class ImageSelection implements Transferable {
 388     private static final int IMAGE = 0;
 389     private static final DataFlavor[] flavors = {DataFlavor.imageFlavor};
 390     private Image data;
 391 
 392     public ImageSelection(Image data) {
 393         this.data = data;
 394     }
 395 
 396     @Override
 397     public DataFlavor[] getTransferDataFlavors() {
 398         // returning flavors itself would allow client code to modify
 399         // our internal behavior
 400         return flavors.clone();
 401     }
 402 
 403     @Override
 404     public boolean isDataFlavorSupported(DataFlavor flavor) {
 405         return Stream.of(flavor).anyMatch(flavor::equals);
 406     }
 407 
 408     @Override
 409     public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {
 410         if (flavor.equals(flavors[IMAGE])) {
 411             return data;
 412         } else {
 413             throw new UnsupportedFlavorException(flavor);
 414         }
 415     }
 416 }