8037371: [macosx] Test closed/java/awt/dnd/ImageTransferTest/ImageTransferTest.html fails
authorpchelko
Fri, 14 Mar 2014 17:48:28 +0400
changeset 23652 11515e3c3f85
parent 23651 e41298d0da2f
child 23653 a90ac2d7896c
8037371: [macosx] Test closed/java/awt/dnd/ImageTransferTest/ImageTransferTest.html fails Reviewed-by: anthony, serb
jdk/src/macosx/classes/sun/lwawt/macosx/CDataTransferer.java
jdk/src/macosx/classes/sun/lwawt/macosx/CImage.java
jdk/src/macosx/native/sun/awt/CDataTransferer.m
jdk/src/macosx/native/sun/awt/CDragSource.m
jdk/src/macosx/native/sun/awt/CDropTarget.m
jdk/src/macosx/native/sun/awt/CImage.m
jdk/test/java/awt/dnd/ImageTransferTest/ImageTransferTest.java
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CDataTransferer.java	Fri Mar 14 16:01:04 2014 +0400
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CDataTransferer.java	Fri Mar 14 17:48:28 2014 +0400
@@ -52,7 +52,9 @@
         "RICH_TEXT",
         "HTML",
         "PDF",
-        "URL"
+        "URL",
+        "PNG",
+        "JFIF"
     };
 
     static {
@@ -74,8 +76,8 @@
     public static final int CF_HTML        = 5;
     public static final int CF_PDF         = 6;
     public static final int CF_URL         = 7;
-    public static final int CF_PNG         = 10;
-    public static final int CF_JPEG        = 11;
+    public static final int CF_PNG         = 8;
+    public static final int CF_JPEG        = 9;
 
     private CDataTransferer() {}
 
@@ -204,20 +206,9 @@
         return handler;
     }
 
-    private native byte[] imageDataToPlatformImageBytes(int[] rData, int nW, int nH);
     @Override
     protected byte[] imageToPlatformBytes(Image image, long format) {
-        int w = image.getWidth(null);
-        int h = image.getHeight(null);
-        BufferedImage bimage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB_PRE);
-        Graphics g = bimage.getGraphics();
-        g.drawImage(image, 0, 0, w, h, null);
-        g.dispose();
-        Raster raster = bimage.getRaster();
-        DataBuffer buffer = raster.getDataBuffer();
-        return imageDataToPlatformImageBytes(((DataBufferInt)buffer).getData(),
-                                             raster.getWidth(),
-                                             raster.getHeight());
+        return CImage.getCreator().getPlatformImageBytes(image);
     }
 
     private static native String[] nativeDragQueryFile(final byte[] bytes);
@@ -228,14 +219,9 @@
         return nativeDragQueryFile(bytes);
     }
 
-    private native Image getImageForByteStream(byte[] bytes);
-    /**
-     * Translates a byte array which contains
-     * platform-specific image data in the given format into an Image.
-     */
     @Override
     protected Image platformImageBytesToImage(byte[] bytes, long format) throws IOException {
-        return getImageForByteStream(bytes);
+        return CImage.getCreator().createImageFromPlatformImageBytes(bytes);
     }
 
     @Override
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CImage.java	Fri Mar 14 16:01:04 2014 +0400
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CImage.java	Fri Mar 14 17:48:28 2014 +0400
@@ -38,11 +38,13 @@
 
 public class CImage extends CFRetainedResource {
     private static native long nativeCreateNSImageFromArray(int[] buffer, int w, int h);
+    private static native long nativeCreateNSImageFromBytes(byte[] buffer);
     private static native long nativeCreateNSImageFromArrays(int[][] buffers, int w[], int h[]);
     private static native long nativeCreateNSImageFromFileContents(String file);
     private static native long nativeCreateNSImageOfFileFromLaunchServices(String file);
     private static native long nativeCreateNSImageFromImageName(String name);
     private static native long nativeCreateNSImageFromIconSelector(int selector);
+    private static native byte[] nativeGetPlatformImageBytes(int[] buffer, int w, int h);
     private static native void nativeCopyNSImageIntoArray(long image, int[] buffer, int sw, int sh, int dw, int dh);
     private static native Dimension2D nativeGetNSImageSize(long image);
     private static native void nativeSetNSImageSize(long image, double w, double h);
@@ -147,6 +149,23 @@
                                                            image.getHeight(null)));
         }
 
+        public byte[] getPlatformImageBytes(final Image image) {
+            int[] buffer = imageToArray(image, false);
+
+            if (buffer == null) {
+                return null;
+            }
+
+            return nativeGetPlatformImageBytes(buffer, image.getWidth(null), image.getHeight(null));
+        }
+
+        /**
+         * Translates a byte array which contains platform-specific image data in the given format into an Image.
+         */
+        public Image createImageFromPlatformImageBytes(final byte[] buffer) {
+            return createImageUsingNativeSize(nativeCreateNSImageFromBytes(buffer));
+        }
+
         // This is used to create a CImage from a Image
         public CImage createFromImage(final Image image) {
             if (image instanceof MultiResolutionImage) {
--- a/jdk/src/macosx/native/sun/awt/CDataTransferer.m	Fri Mar 14 16:01:04 2014 +0400
+++ b/jdk/src/macosx/native/sun/awt/CDataTransferer.m	Fri Mar 14 17:48:28 2014 +0400
@@ -54,6 +54,10 @@
                               forKey:[NSNumber numberWithLong:sun_lwawt_macosx_CDataTransferer_CF_PDF]];
         [sStandardMappings setObject:NSURLPboardType
                               forKey:[NSNumber numberWithLong:sun_lwawt_macosx_CDataTransferer_CF_URL]];
+        [sStandardMappings setObject:NSPasteboardTypePNG
+                              forKey:[NSNumber numberWithLong:sun_lwawt_macosx_CDataTransferer_CF_PNG]];
+        [sStandardMappings setObject:(NSString*)kUTTypeJPEG
+                              forKey:[NSNumber numberWithLong:sun_lwawt_macosx_CDataTransferer_CF_JPEG]];
     }
     return sStandardMappings;
 }
@@ -126,106 +130,6 @@
     return returnValue;
 }
 
-/*
- * Class:     sun_lwawt_macosx_CDataTransferer
- * Method:    imageDataToPlatformImageBytes
- * Signature: ([III)[B
-     */
-JNIEXPORT jbyteArray JNICALL Java_sun_lwawt_macosx_CDataTransferer_imageDataToPlatformImageBytes
-(JNIEnv *env, jobject obj, jintArray inPixelData, jint inWidth, jint inHeight)
-{
-    jbyteArray returnValue = nil;
-JNF_COCOA_ENTER(env);
-    UInt32 *rawImageData = (UInt32 *)(*env)->GetPrimitiveArrayCritical(env, inPixelData, 0);
-
-    // The pixel data is in premultiplied ARGB format. That's exactly what
-    // we need for the bitmap image rep.
-    if (rawImageData != NULL) {
-        NSBitmapImageRep *imageRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL
-                                                                             pixelsWide:inWidth
-                                                                             pixelsHigh:inHeight
-                                                                          bitsPerSample:8
-                                                                        samplesPerPixel:4
-                                                                               hasAlpha:YES
-                                                                               isPlanar:NO
-                                                                         colorSpaceName:NSCalibratedRGBColorSpace
-                                                                            bytesPerRow:(inWidth*4)
-                                                                           bitsPerPixel:32];
-
-        // Conver the ARGB data into RGBA data that the bitmap can draw.
-        unsigned char *destData = [imageRep bitmapData];
-        unsigned char *currentRowBase;
-        jint x, y;
-
-        for (y = 0; y < inHeight; y++) {
-            currentRowBase = destData + y * (inWidth * 4);
-            unsigned char *currElement = currentRowBase;
-            for (x = 0; x < inWidth; x++) {
-                UInt32 currPixel = rawImageData[y * inWidth + x];
-                *currElement++ = ((currPixel & 0xFF0000) >> 16);
-                *currElement++ = ((currPixel & 0xFF00) >> 8);
-                *currElement++ = (currPixel & 0xFF);
-                *currElement++ = ((currPixel & 0xFF000000) >> 24);
-            }
-        }
-
-        (*env)->ReleasePrimitiveArrayCritical(env, inPixelData, rawImageData, JNI_ABORT);
-        NSData *tiffImage = [imageRep TIFFRepresentation];
-        jsize tiffSize = (jsize)[tiffImage length]; // #warning 64-bit: -length returns NSUInteger, but NewByteArray takes jsize
-        returnValue = (*env)->NewByteArray(env, tiffSize);
-        CHECK_NULL_RETURN(returnValue, nil);
-        jbyte *tiffData = (jbyte *)(*env)->GetPrimitiveArrayCritical(env, returnValue, 0);
-        CHECK_NULL_RETURN(tiffData, nil);
-        [tiffImage getBytes:tiffData];
-        (*env)->ReleasePrimitiveArrayCritical(env, returnValue, tiffData, 0); // Do not use JNI_COMMIT, as that will not free the buffer copy when +ProtectJavaHeap is on.
-        [imageRep release];
-    }
-JNF_COCOA_EXIT(env);
-    return returnValue;
-
-}
-
-static jobject getImageForByteStream(JNIEnv *env, jbyteArray sourceData)
-{
-    CHECK_NULL_RETURN(sourceData, NULL);
-
-    jsize sourceSize = (*env)->GetArrayLength(env, sourceData);
-    if (sourceSize == 0) return NULL;
-
-    jbyte *sourceBytes = (*env)->GetPrimitiveArrayCritical(env, sourceData, NULL);
-    CHECK_NULL_RETURN(sourceBytes, NULL);
-    NSData *rawData = [NSData dataWithBytes:sourceBytes length:sourceSize];
-
-    NSImage *newImage = [[NSImage alloc] initWithData:rawData];
-
-    (*env)->ReleasePrimitiveArrayCritical(env, sourceData, sourceBytes, JNI_ABORT);
-    CHECK_NULL_RETURN(newImage, NULL);
-
-    // The ownership of the NSImage is passed to the new CImage jobject. No need to release it.
-    static JNF_CLASS_CACHE(jc_CImage, "sun/lwawt/macosx/CImage");
-    static JNF_STATIC_MEMBER_CACHE(jm_CImage_getCreator, jc_CImage, "getCreator", "()Lsun/lwawt/macosx/CImage$Creator;");
-    jobject creator = JNFCallStaticObjectMethod(env, jm_CImage_getCreator);
-
-    static JNF_CLASS_CACHE(jc_CImage_Generator, "sun/lwawt/macosx/CImage$Creator");
-    static JNF_MEMBER_CACHE(jm_CImage_Generator_createImageUsingNativeSize, jc_CImage_Generator, "createImageUsingNativeSize", "(J)Ljava/awt/image/BufferedImage;");
-    return JNFCallObjectMethod(env, creator, jm_CImage_Generator_createImageUsingNativeSize, ptr_to_jlong(newImage)); // AWT_THREADING Safe (known object)
-}
-
-/*
- * Class:     sun_lwawt_macosx_CDataTransferer
- * Method:    getImageForByteStream
- * Signature: ([B)Ljava/awt/Image;
- */
-JNIEXPORT jobject JNICALL Java_sun_lwawt_macosx_CDataTransferer_getImageForByteStream
-  (JNIEnv *env, jobject obj, jbyteArray sourceData)
-{
-    jobject img = NULL;
-JNF_COCOA_ENTER(env);
-    img = getImageForByteStream(env, sourceData);
-JNF_COCOA_EXIT(env);
-    return img;
-}
-
 static jobjectArray CreateJavaFilenameArray(JNIEnv *env, NSArray *filenameArray)
 {
     NSUInteger filenameCount = [filenameArray count];
--- a/jdk/src/macosx/native/sun/awt/CDragSource.m	Fri Mar 14 16:01:04 2014 +0400
+++ b/jdk/src/macosx/native/sun/awt/CDragSource.m	Fri Mar 14 17:48:28 2014 +0400
@@ -311,8 +311,7 @@
 
                     // This is a good approximation if not perfect. A conclusive search would
                     // have to be done matching all defined strings in AppKit's commonStrings.h.
-                    if ([type hasPrefix:@"NS"] || [type hasPrefix:@"NeXT"])
-                        hasNSTypeData = true;
+                    hasNSTypeData = [type hasPrefix:@"NS"] || [type hasPrefix:@"NeXT"] || [type hasPrefix:@"public."];
                 }
             }
         }
--- a/jdk/src/macosx/native/sun/awt/CDropTarget.m	Fri Mar 14 16:01:04 2014 +0400
+++ b/jdk/src/macosx/native/sun/awt/CDropTarget.m	Fri Mar 14 17:48:28 2014 +0400
@@ -106,6 +106,7 @@
         NSFilenamesPboardType,
         NSPostScriptPboardType,
         NSTIFFPboardType,
+        NSPasteboardTypePNG,
         NSRTFPboardType,
         NSTabularTextPboardType,
         NSFontPboardType,
@@ -119,6 +120,7 @@
         NSVCardPboardType,
         NSFilesPromisePboardType,
         [DnDUtilities javaPboardType],
+        (NSString*)kUTTypeJPEG,
         nil];
 
     // Enable dragging events over this object:
--- a/jdk/src/macosx/native/sun/awt/CImage.m	Fri Mar 14 16:01:04 2014 +0400
+++ b/jdk/src/macosx/native/sun/awt/CImage.m	Fri Mar 14 17:48:28 2014 +0400
@@ -112,7 +112,7 @@
     jlong result = 0L;
 
 JNF_COCOA_ENTER(env);
-
+    
     NSBitmapImageRep* imageRep = CImage_CreateImageRep(env, buffer, width, height);
     if (imageRep) {
         NSImage *nsImage = [[[NSImage alloc] initWithSize:NSMakeSize(width, height)] retain];
@@ -422,3 +422,62 @@
 
     return jreturnArray;
 }
+
+/*
+ * Class:     sun_lwawt_macosx_CImage
+ * Method:    nativeGetPlatformImageBytes
+ * Signature: ([III)[B
+ */
+JNIEXPORT jbyteArray JNICALL Java_sun_lwawt_macosx_CImage_nativeGetPlatformImageBytes
+(JNIEnv *env, jclass klass, jintArray buffer, jint width, jint height)
+{
+    jbyteArray result = 0L;
+
+    JNF_COCOA_ENTER(env);
+
+    NSBitmapImageRep* imageRep = [CImage_CreateImageRep(env, buffer, width, height) autorelease];
+    if (imageRep) {
+        NSData *tiffImage = [imageRep TIFFRepresentation];
+        jsize tiffSize = (jsize)[tiffImage length];
+        result = (*env)->NewByteArray(env, tiffSize);
+        CHECK_NULL_RETURN(result, nil);
+        jbyte *tiffData = (jbyte *)(*env)->GetPrimitiveArrayCritical(env, result, 0);
+        CHECK_NULL_RETURN(tiffData, nil);
+        [tiffImage getBytes:tiffData];
+        (*env)->ReleasePrimitiveArrayCritical(env, result, tiffData, 0);
+    }
+
+    JNF_COCOA_EXIT(env);
+
+    return result;
+}
+
+/*
+ * Class:     sun_lwawt_macosx_CImage
+ * Method:    nativeCreateNSImageFromBytes
+ * Signature: ([B)J
+ */
+JNIEXPORT jlong JNICALL Java_sun_lwawt_macosx_CImage_nativeCreateNSImageFromBytes
+(JNIEnv *env, jclass klass, jbyteArray sourceData)
+{
+    jlong result = 0L;
+    CHECK_NULL_RETURN(sourceData, 0L);
+
+    JNF_COCOA_ENTER(env);
+
+    jsize sourceSize = (*env)->GetArrayLength(env, sourceData);
+    if (sourceSize == 0) return 0L;
+
+    jbyte *sourceBytes = (*env)->GetPrimitiveArrayCritical(env, sourceData, NULL);
+    CHECK_NULL_RETURN(sourceBytes, 0L);
+    NSData *rawData = [NSData dataWithBytes:sourceBytes length:sourceSize];
+    NSImage *newImage = [[NSImage alloc] initWithData:rawData];
+
+    (*env)->ReleasePrimitiveArrayCritical(env, sourceData, sourceBytes, JNI_ABORT);
+    CHECK_NULL_RETURN(newImage, 0L);
+
+    result = ptr_to_jlong(newImage);
+    JNF_COCOA_EXIT(env);
+
+    return result;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/dnd/ImageTransferTest/ImageTransferTest.java	Fri Mar 14 17:48:28 2014 +0400
@@ -0,0 +1,412 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+  @test
+  @bug 4397404 4720930
+  @summary tests that images of all supported native image formats are transfered properly
+  @library ../../regtesthelpers/process/
+  @build ProcessResults ProcessCommunicator
+  @author gas@sparc.spb.su area=Clipboard
+  @run main ImageTransferTest
+*/
+
+import sun.awt.OSInfo;
+import sun.awt.SunToolkit;
+import test.java.awt.regtesthelpers.process.ProcessCommunicator;
+import test.java.awt.regtesthelpers.process.ProcessResults;
+
+import java.awt.*;
+import java.awt.datatransfer.DataFlavor;
+import java.awt.datatransfer.SystemFlavorMap;
+import java.awt.datatransfer.Transferable;
+import java.awt.datatransfer.UnsupportedFlavorException;
+import java.awt.dnd.DnDConstants;
+import java.awt.dnd.DragSource;
+import java.awt.dnd.DragSourceAdapter;
+import java.awt.dnd.DragSourceDropEvent;
+import java.awt.dnd.DragSourceListener;
+import java.awt.dnd.DropTarget;
+import java.awt.dnd.DropTargetAdapter;
+import java.awt.dnd.DropTargetDropEvent;
+import java.awt.event.InputEvent;
+import java.awt.image.BufferedImage;
+import java.awt.image.MemoryImageSource;
+import java.util.stream.Stream;
+
+public class ImageTransferTest {
+    public static void main(String[] arg) throws Exception {
+        ImageDragSource ids = new ImageDragSource();
+        ids.frame.setLocation(100, 100);
+        ids.frame.setVisible(true);
+        Util.sync();
+        String classpath = System.getProperty("java.class.path");
+        String[] args = new String[ids.formats.length + 4];
+        args[0] = "200";
+        args[1] = "100";
+        args[2] = args[3] = "150";
+
+        System.arraycopy(ids.formats, 0, args, 4, ids.formats.length);
+        ProcessResults pres = ProcessCommunicator.executeChildProcess(ImageDropTarget.class, classpath, args);
+
+        if (pres.getStdErr() != null && pres.getStdErr().length() > 0) {
+            System.err.println("========= Child VM System.err ========");
+            System.err.print(pres.getStdErr());
+            System.err.println("======================================");
+        }
+
+        if (pres.getStdOut() != null && pres.getStdOut().length() > 0) {
+            System.err.println("========= Child VM System.out ========");
+            System.err.print(pres.getStdOut());
+            System.err.println("======================================");
+        }
+
+        boolean failed = false;
+        String passedFormats = "";
+        String failedFormats = "";
+
+        for (int i = 0; i < ids.passedArray.length; i++) {
+            if (ids.passedArray[i]) passedFormats += ids.formats[i] + " ";
+            else {
+                failed = true;
+                failedFormats += ids.formats[i] + " ";
+            }
+        }
+
+        if (failed) {
+            throw new RuntimeException("test failed: images in following " +
+                    "native formats are not transferred properly: " + failedFormats);
+        } else {
+            System.err.println("images in following " +
+                    "native formats are transferred properly: " + passedFormats);
+        }
+    }
+}
+
+
+class Util {
+    public static void sync() {
+        ((SunToolkit) Toolkit.getDefaultToolkit()).realSync();
+        try {
+            Thread.sleep(500);
+        } catch (InterruptedException e) {
+            throw new RuntimeException(e);
+        }
+    }
+}
+
+abstract class ImageTransferer {
+    Image image;
+    String[] formats;
+    int fi; // current format index
+    Frame frame = new Frame();
+
+
+    ImageTransferer() {
+        image = createImage();
+        frame.setSize(100, 100);
+    }
+
+    private static Image createImage() {
+        int w = 100;
+        int h = 100;
+        int[] pix = new int[w * h];
+
+        int index = 0;
+        for (int y = 0; y < h; y++) {
+            for (int x = 0; x < w; x++) {
+                int red = 127;
+                int green = 127;
+                int blue = y > h / 2 ? 127 : 0;
+                int alpha = 255;
+                if (x < w / 4 && y < h / 4) {
+                    alpha = 0;
+                    red = 0;
+                }
+                pix[index++] = (alpha << 24) | (red << 16) | (green << 8) | blue;
+            }
+        }
+        return Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(w, h, pix, 0, w));
+    }
+
+
+    static String[] retrieveFormatsToTest() {
+        SystemFlavorMap sfm = (SystemFlavorMap) SystemFlavorMap.getDefaultFlavorMap();
+        java.util.List<String> ln = sfm.getNativesForFlavor(DataFlavor.imageFlavor);
+        if (OSInfo.OSType.WINDOWS.equals(OSInfo.getOSType()) && !ln.contains("METAFILEPICT")) {
+            // for test failing on JDK without this fix
+            ln.add("METAFILEPICT");
+        }
+        return ln.toArray(new String[ln.size()]);
+    }
+
+    static void leaveFormat(String format) {
+        SystemFlavorMap sfm = (SystemFlavorMap) SystemFlavorMap.getDefaultFlavorMap();
+        sfm.setFlavorsForNative(format, new DataFlavor[]{DataFlavor.imageFlavor});
+        sfm.setNativesForFlavor(DataFlavor.imageFlavor, new String[]{format});
+    }
+
+
+    boolean areImagesIdentical(Image im1, Image im2) {
+        if (formats[fi].equals("JFIF") || formats[fi].equals("image/jpeg") ||
+                formats[fi].equals("GIF") || formats[fi].equals("image/gif")) {
+            // JFIF and GIF are lossy formats
+            return true;
+        }
+        int[] ib1 = getImageData(im1);
+        int[] ib2 = getImageData(im2);
+
+        if (ib1.length != ib2.length) {
+            return false;
+        }
+
+        if (formats[fi].equals("PNG") ||
+                formats[fi].equals("image/png") ||
+                formats[fi].equals("image/x-png")) {
+            // check alpha as well
+            for (int i = 0; i < ib1.length; i++) {
+                if (ib1[i] != ib2[i]) {
+                    System.err.println("different pixels: " +
+                            Integer.toHexString(ib1[i]) + " " +
+                            Integer.toHexString(ib2[i]));
+                    return false;
+                }
+            }
+        } else {
+            for (int i = 0; i < ib1.length; i++) {
+                if ((ib1[i] & 0x00FFFFFF) != (ib2[i] & 0x00FFFFFF)) {
+                    System.err.println("different pixels: " +
+                            Integer.toHexString(ib1[i]) + " " +
+                            Integer.toHexString(ib2[i]));
+                    return false;
+                }
+            }
+        }
+        return true;
+    }
+
+    private static int[] getImageData(Image image) {
+        int width = image.getWidth(null);
+        int height = image.getHeight(null);
+        BufferedImage bimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
+        Graphics2D g2d = bimage.createGraphics();
+        try {
+            g2d.drawImage(image, 0, 0, width, height, null);
+        } finally {
+            g2d.dispose();
+        }
+        return bimage.getRGB(0, 0, width, height, null, 0, width);
+    }
+
+    public static int sign(int n) {
+        return n < 0 ? -1 : n == 0 ? 0 : 1;
+    }
+
+}
+
+
+class ImageDragSource extends ImageTransferer {
+    boolean[] passedArray;
+
+    ImageDragSource() {
+        formats = retrieveFormatsToTest();
+        passedArray = new boolean[formats.length];
+        final DragSourceListener dsl = new DragSourceAdapter() {
+            public void dragDropEnd(DragSourceDropEvent e) {
+                System.err.println("Drop was successful=" + e.getDropSuccess());
+                notifyTransferSuccess(e.getDropSuccess());
+                if (++fi < formats.length) {
+                    leaveFormat(formats[fi]);
+                }
+            }
+        };
+
+        new DragSource().createDefaultDragGestureRecognizer(frame,
+                DnDConstants.ACTION_COPY,
+                dge -> dge.startDrag(null, new ImageSelection(image), dsl));
+        leaveFormat(formats[fi]);
+    }
+
+
+    void notifyTransferSuccess(boolean status) {
+        passedArray[fi] = status;
+    }
+}
+
+
+class ImageDropTarget extends ImageTransferer {
+    private final Robot robot;
+    private static Point startPoint, endPoint = new Point(250, 150);
+
+    ImageDropTarget() throws AWTException {
+        DropTargetAdapter dropTargetAdapter = new DropTargetAdapter() {
+            @Override
+            public void drop(DropTargetDropEvent dtde) {
+                checkImage(dtde);
+                startImageDrag();
+            }
+        };
+        new DropTarget(frame, dropTargetAdapter);
+        robot = new Robot();
+    }
+
+
+    void checkImage(DropTargetDropEvent dtde) {
+        final Transferable t = dtde.getTransferable();
+        if (t.isDataFlavorSupported(DataFlavor.imageFlavor)) {
+            dtde.acceptDrop(DnDConstants.ACTION_COPY);
+            Image im;
+            try {
+                im = (Image) t.getTransferData(DataFlavor.imageFlavor);
+                System.err.println("getTransferData was successful");
+            } catch (Exception e) {
+                System.err.println("Can't getTransferData: " + e);
+                dtde.dropComplete(false);
+                notifyTransferSuccess(false);
+                return;
+            }
+
+            if (im == null) {
+                System.err.println("getTransferData returned null");
+                dtde.dropComplete(false);
+                notifyTransferSuccess(false);
+            } else if (areImagesIdentical(image, im)) {
+                dtde.dropComplete(true);
+                notifyTransferSuccess(true);
+            } else {
+                System.err.println("transferred image is different from initial image");
+                dtde.dropComplete(false);
+                notifyTransferSuccess(false);
+            }
+
+        } else {
+            System.err.println("imageFlavor is not supported by Transferable");
+            dtde.rejectDrop();
+            notifyTransferSuccess(false);
+        }
+    }
+
+    void startImageDrag() {
+        leaveFormat(formats[fi]);
+        new Thread(() -> {
+            try {
+                Thread.sleep(1000);
+            } catch (InterruptedException e) {
+                e.printStackTrace();
+                // Exit from the child process
+                System.exit(1);
+            }
+            robot.mouseMove(startPoint.x, startPoint.y);
+            robot.mousePress(InputEvent.BUTTON1_MASK);
+            for (Point p = new Point(startPoint); !p.equals(endPoint);
+                 p.translate(sign(endPoint.x - p.x), sign(endPoint.y - p.y))) {
+                robot.mouseMove(p.x, p.y);
+                try {
+                    Thread.sleep(50);
+                } catch (InterruptedException e) {
+                    e.printStackTrace();
+                }
+            }
+
+            robot.mouseRelease(InputEvent.BUTTON1_MASK);
+        }).start();
+    }
+
+    void notifyTransferSuccess(boolean status) {
+        if (status) {
+            System.err.println("format passed: " + formats[fi]);
+        } else {
+            System.err.println("format failed: " + formats[fi]);
+            System.exit(1);
+        }
+        if (fi < formats.length - 1) {
+            leaveFormat(formats[++fi]);
+        } else {
+            new Thread(() -> {
+                try {
+                    Thread.sleep(500);
+                } catch (InterruptedException e) {
+                    e.printStackTrace();
+                }
+                System.exit(0);
+            }).start();
+        }
+    }
+
+
+    public static void main(String[] args) {
+        try {
+            ImageDropTarget idt = new ImageDropTarget();
+
+            int x = Integer.parseInt(args[0]);
+            int y = Integer.parseInt(args[1]);
+            startPoint = new Point(Integer.parseInt(args[2]), Integer.parseInt(args[3]));
+
+            idt.formats = new String[args.length - 4];
+            System.arraycopy(args, 4, idt.formats, 0, args.length - 4);
+            leaveFormat(idt.formats[0]);
+
+            idt.frame.setLocation(x, y);
+            idt.frame.setVisible(true);
+            Util.sync();
+
+            idt.startImageDrag();
+        } catch (Throwable e) {
+            e.printStackTrace();
+            System.exit(1);
+        }
+    }
+
+}
+
+
+class ImageSelection implements Transferable {
+    private static final int IMAGE = 0;
+    private static final DataFlavor[] flavors = {DataFlavor.imageFlavor};
+    private Image data;
+
+    public ImageSelection(Image data) {
+        this.data = data;
+    }
+
+    @Override
+    public DataFlavor[] getTransferDataFlavors() {
+        // returning flavors itself would allow client code to modify
+        // our internal behavior
+        return flavors.clone();
+    }
+
+    @Override
+    public boolean isDataFlavorSupported(DataFlavor flavor) {
+        return Stream.of(flavor).anyMatch(flavor::equals);
+    }
+
+    @Override
+    public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {
+        if (flavor.equals(flavors[IMAGE])) {
+            return data;
+        } else {
+            throw new UnsupportedFlavorException(flavor);
+        }
+    }
+}