1 /*
   2  * Copyright (c) 2014, 2018, 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  * @key headful
  27  * @bug 4397404 4720930 8197926 8176556
  28  * @summary tests that images of all supported native image formats are
  29  * transferred properly
  30  * @library /test/lib
  31  * @library ../../regtesthelpers/process/
  32  * @build jdk.test.lib.Platform ProcessResults ProcessCommunicator
  33  * @author gas@sparc.spb.su area=Clipboard
  34  * @run main/timeout=240 ImageTransferTest
  35  */
  36 
  37 import jdk.test.lib.Platform;
  38 import test.java.awt.regtesthelpers.process.ProcessCommunicator;
  39 import test.java.awt.regtesthelpers.process.ProcessResults;
  40 
  41 import java.awt.*;
  42 import java.awt.datatransfer.DataFlavor;
  43 import java.awt.datatransfer.SystemFlavorMap;
  44 import java.awt.datatransfer.Transferable;
  45 import java.awt.datatransfer.UnsupportedFlavorException;
  46 import java.awt.dnd.DnDConstants;
  47 import java.awt.dnd.DragSource;
  48 import java.awt.dnd.DragSourceAdapter;
  49 import java.awt.dnd.DragSourceDropEvent;
  50 import java.awt.dnd.DragSourceListener;
  51 import java.awt.dnd.DropTarget;
  52 import java.awt.dnd.DropTargetAdapter;
  53 import java.awt.dnd.DropTargetDropEvent;
  54 import java.awt.event.InputEvent;
  55 import java.awt.image.BufferedImage;
  56 import java.awt.image.MemoryImageSource;
  57 import java.util.stream.Stream;
  58 
  59 public class ImageTransferTest {
  60     public static void main(String[] arg) throws Exception {
  61         ImageDragSource ids = new ImageDragSource();
  62         try {
  63             ids.frame.setUndecorated(true);
  64             ids.frame.setLocation(100, 100);
  65             ids.frame.setVisible(true);
  66             Util.sync();
  67             String classpath = System.getProperty("java.class.path");
  68             String[] args = new String[ids.formats.length + 4];
  69             args[0] = "200";
  70             args[1] = "100";
  71             args[2] = args[3] = "150";
  72 
  73             System.arraycopy(ids.formats, 0, args, 4, ids.formats.length);
  74             String scale = System.getProperty("sun.java2d.uiScale");
  75             ProcessResults pres = ProcessCommunicator.
  76                     executeChildProcess(ImageDropTarget.class, classpath +
  77                     " -Dsun.java2d.uiScale=" + scale, args);
  78 
  79             if (pres.getStdErr() != null && pres.getStdErr().length() > 0) {
  80                 System.err.println("========= Child VM System.err ========");
  81                 System.err.print(pres.getStdErr());
  82                 System.err.println("======================================");
  83             }
  84 
  85             if (pres.getStdOut() != null && pres.getStdOut().length() > 0) {
  86                 System.err.println("========= Child VM System.out ========");
  87                 System.err.print(pres.getStdOut());
  88                 System.err.println("======================================");
  89             }
  90 
  91             boolean failed = false;
  92             String passedFormats = "";
  93             String failedFormats = "";
  94 
  95             for (int i = 0; i < ids.passedArray.length; i++) {
  96                 if (ids.passedArray[i]) passedFormats += ids.formats[i] + " ";
  97                 else {
  98                     failed = true;
  99                     failedFormats += ids.formats[i] + " ";
 100                 }
 101             }
 102 
 103             if (failed) {
 104                 throw new RuntimeException("test failed: images in following " +
 105                 "native formats are not transferred properly: " +
 106                 failedFormats);
 107             } else {
 108                 System.err.println("images in following " +
 109                 "native formats are transferred properly: " + passedFormats);
 110             }
 111         } finally {
 112             if (ids.frame != null) {
 113                 ids.frame.dispose();
 114             }
 115         }
 116     }
 117 }
 118 
 119 
 120 class Util {
 121     private static Robot srobot = null;
 122     public static void sync() {
 123         try {
 124             if(srobot == null) {
 125                 srobot = new Robot();
 126             }
 127             srobot.waitForIdle();
 128             Thread.sleep(500);
 129         } catch (Exception e) {
 130             throw new RuntimeException(e);
 131         }
 132     }
 133 }
 134 
 135 abstract class ImageTransferer {
 136     Image image;
 137     Image imageForJpeg;
 138     String[] formats;
 139     int fi; // current format index
 140     Frame frame = new Frame();
 141 
 142 
 143     ImageTransferer() {
 144         image = createImage(false);
 145         imageForJpeg = createImage(true);
 146         frame.setSize(100, 100);
 147     }
 148 
 149     private static Image createImage(boolean forJpeg) {
 150         int w = 100;
 151         int h = 100;
 152         int[] pix = new int[w * h];
 153 
 154         BufferedImage img;
 155         if (!forJpeg) {
 156             img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
 157         } else {
 158             img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
 159         }
 160         int index = 0;
 161         for (int y = 0; y < h; y++) {
 162             for (int x = 0; x < w; x++) {
 163                 int red = 127;
 164                 int green = 127;
 165                 int blue = y > h / 2 ? 127 : 0;
 166                 int alpha = 255;
 167                 if (x < w / 4 && y < h / 4) {
 168                     alpha = 0;
 169                     red = 0;
 170                 }
 171                 if (!forJpeg) {
 172                     pix[index] =
 173                         (alpha <<24) | (red << 16) | (green << 8) | blue;
 174                 } else {
 175                     pix[index] =
 176                         (red << 16) | (green << 8) | blue;
 177                 }
 178                 img.setRGB(x, y, pix[index]);
 179                 index++;
 180             }
 181         }
 182         return (Image)img;

 183     }
 184 
 185 
 186     static String[] retrieveFormatsToTest() {
 187         SystemFlavorMap sfm =
 188                 (SystemFlavorMap) SystemFlavorMap.getDefaultFlavorMap();
 189         java.util.List<String> ln =
 190                 sfm.getNativesForFlavor(DataFlavor.imageFlavor);
 191         if (Platform.isWindows() &&  !ln.contains("METAFILEPICT"))
 192         {
 193             // for test failing on JDK without this fix
 194             ln.add("METAFILEPICT");
 195         }
 196         return ln.toArray(new String[ln.size()]);
 197     }
 198 
 199     static void leaveFormat(String format) {
 200         SystemFlavorMap sfm =
 201                 (SystemFlavorMap) SystemFlavorMap.getDefaultFlavorMap();
 202         sfm.setFlavorsForNative(format,
 203                                 new DataFlavor[]{DataFlavor.imageFlavor});
 204         sfm.setNativesForFlavor(DataFlavor.imageFlavor, new String[]{format});
 205     }
 206 
 207 
 208     boolean areImagesIdentical(Image im1, Image im2) {
 209         if (formats[fi].equals("JFIF") || formats[fi].equals("image/jpeg") ||
 210             formats[fi].equals("GIF") || formats[fi].equals("image/gif")) {
 211             // JFIF and GIF are lossy formats
 212             return true;
 213         }
 214         int[] ib1 = getImageData(im1);
 215         int[] ib2 = getImageData(im2);
 216 
 217         if (ib1.length != ib2.length) {
 218             return false;
 219         }
 220 
 221         if (formats[fi].equals("PNG") ||
 222             formats[fi].equals("image/png") ||
 223             formats[fi].equals("image/x-png")) {
 224             // check alpha as well
 225             for (int i = 0; i < ib1.length; i++) {
 226                 if (ib1[i] != ib2[i]) {
 227                     System.err.println("different pixels: " +
 228                     Integer.toHexString(ib1[i]) + " " +
 229                     Integer.toHexString(ib2[i]));
 230                     return false;
 231                 }
 232             }
 233         } else {
 234             for (int i = 0; i < ib1.length; i++) {
 235                 if ((ib1[i] & 0x00FFFFFF) != (ib2[i] & 0x00FFFFFF)) {
 236                     System.err.println("different pixels: " +
 237                     Integer.toHexString(ib1[i]) + " " +
 238                     Integer.toHexString(ib2[i]));
 239                     return false;
 240                 }
 241             }
 242         }
 243         return true;
 244     }
 245 
 246     private static int[] getImageData(Image image) {
 247         int width = image.getWidth(null);
 248         int height = image.getHeight(null);
 249         BufferedImage bimage =
 250                 new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
 251         Graphics2D g2d = bimage.createGraphics();
 252         try {
 253             g2d.drawImage(image, 0, 0, width, height, null);
 254         } finally {
 255             g2d.dispose();
 256         }
 257         return bimage.getRGB(0, 0, width, height, null, 0, width);
 258     }
 259 
 260     public static int sign(int n) {
 261         return n < 0 ? -1 : n == 0 ? 0 : 1;
 262     }
 263 
 264 }
 265 
 266 
 267 class ImageDragSource extends ImageTransferer {
 268     boolean[] passedArray;
 269 
 270     ImageDragSource() {
 271         formats = retrieveFormatsToTest();
 272         passedArray = new boolean[formats.length];
 273         final DragSourceListener dsl = new DragSourceAdapter() {
 274             public void dragDropEnd(DragSourceDropEvent e) {
 275                 System.err.println("Drop was successful=" + e.getDropSuccess());
 276                 notifyTransferSuccess(e.getDropSuccess());
 277                 if (++fi < formats.length) {
 278                     leaveFormat(formats[fi]);
 279                 }
 280             }
 281         };
 282 
 283         new DragSource().createDefaultDragGestureRecognizer(frame,
 284         DnDConstants.ACTION_COPY,
 285         dge -> {
 286             if (formats[fi].equals("JFIF") || formats[fi].equals("image/jpeg")) {
 287                 dge.startDrag(null, new ImageSelection(imageForJpeg), dsl);
 288             } else {
 289                 dge.startDrag(null, new ImageSelection(image), dsl);
 290             }
 291         });
 292         leaveFormat(formats[fi]);
 293     }
 294 
 295 
 296     void notifyTransferSuccess(boolean status) {
 297         passedArray[fi] = status;
 298     }
 299 }
 300 
 301 
 302 class ImageDropTarget extends ImageTransferer {
 303     private final Robot robot;
 304     private static ImageDropTarget idt;
 305     private static Point startPoint, endPoint = new Point(250, 150);
 306     private static int dropCount = 0;
 307 
 308     ImageDropTarget() throws AWTException {
 309         DropTargetAdapter dropTargetAdapter = new DropTargetAdapter() {
 310             @Override
 311             public void drop(DropTargetDropEvent dtde) {
 312                 dropCount++;
 313                 checkImage(dtde);
 314                 startImageDrag();
 315             }
 316         };
 317         new DropTarget(frame, dropTargetAdapter);
 318         robot = new Robot();
 319     }
 320 
 321 
 322     void checkImage(DropTargetDropEvent dtde) {
 323         final Transferable t = dtde.getTransferable();
 324         if (t.isDataFlavorSupported(DataFlavor.imageFlavor)) {
 325             dtde.acceptDrop(DnDConstants.ACTION_COPY);
 326             Image im;
 327             try {
 328                 im = (Image) t.getTransferData(DataFlavor.imageFlavor);
 329                 System.err.println("getTransferData was successful");
 330             } catch (Exception e) {
 331                 System.err.println("Can't getTransferData: " + e);
 332                 dtde.dropComplete(false);
 333                 notifyTransferSuccess(false);
 334                 return;
 335             }
 336 
 337             /*
 338              * We are using RGB source image for jpeg
 339              * because there is no support for alpha channel.
 340              * Also we are not verifying pixel data for jpeg
 341              * in areImagesIdentical() since it is a lossy format.
 342              * So after image drop we are not handling any needed
 343              * special cases for jpeg.
 344              */
 345             if (im == null) {
 346                 System.err.println("getTransferData returned null");
 347                 dtde.dropComplete(false);
 348                 notifyTransferSuccess(false);
 349             } else if (areImagesIdentical(image, im)) {
 350                 dtde.dropComplete(true);
 351                 notifyTransferSuccess(true);
 352             } else {
 353                 System.err.println("transferred image is different from" +
 354                         " initial image");
 355                 dtde.dropComplete(false);
 356                 notifyTransferSuccess(false);
 357             }
 358 
 359         } else {
 360             System.err.println("imageFlavor is not supported by Transferable");
 361             dtde.rejectDrop();
 362             notifyTransferSuccess(false);
 363         }
 364     }
 365 
 366     void startImageDrag() {
 367         leaveFormat(formats[fi]);
 368         new Thread(() -> {
 369             try {
 370                 Thread.sleep(1000);
 371             } catch (InterruptedException e) {
 372                 if (idt.frame != null) {
 373                     idt.frame.dispose();
 374                 }
 375                 e.printStackTrace();
 376                 // Exit from the child process
 377                 System.exit(1);
 378             }
 379             robot.mouseMove(startPoint.x, startPoint.y);
 380             robot.mousePress(InputEvent.BUTTON1_MASK);
 381             for (Point p = new Point(startPoint); !p.equals(endPoint);
 382                  p.translate(sign(endPoint.x - p.x),
 383                  sign(endPoint.y - p.y)))
 384             {
 385                 robot.mouseMove(p.x, p.y);
 386                 try {
 387                     Thread.sleep(50);
 388                 } catch (InterruptedException e) {
 389                     e.printStackTrace();
 390                 }
 391             }
 392 
 393             robot.mouseRelease(InputEvent.BUTTON1_MASK);
 394         }).start();
 395     }
 396 
 397     void notifyTransferSuccess(boolean status) {
 398         if (status) {
 399             System.err.println("format passed: " + formats[fi]);
 400         } else {
 401             if (idt.frame != null) {
 402                 idt.frame.dispose();
 403             }
 404             System.err.println("format failed: " + formats[fi]);
 405             System.exit(1);
 406         }
 407         if (fi < formats.length - 1) {
 408             leaveFormat(formats[++fi]);
 409         } else {
 410             new Thread(() -> {
 411                 try {
 412                     Thread.sleep(500);
 413                 } catch (InterruptedException e) {
 414                     e.printStackTrace();
 415                 }
 416                 System.exit(0);
 417             }).start();
 418         }
 419     }
 420 
 421 
 422     public static void main(String[] args) throws Exception {
 423         idt = new ImageDropTarget();
 424         try {
 425             idt.frame.setUndecorated(true);
 426 
 427             int x = Integer.parseInt(args[0]);
 428             int y = Integer.parseInt(args[1]);
 429             startPoint = new Point(Integer.parseInt(args[2]),
 430                                    Integer.parseInt(args[3]));
 431 
 432             idt.formats = new String[args.length - 4];
 433             System.arraycopy(args, 4, idt.formats, 0, args.length - 4);
 434             leaveFormat(idt.formats[0]);
 435 
 436             idt.frame.setLocation(x, y);
 437             idt.frame.setVisible(true);
 438             Util.sync();
 439 
 440             idt.startImageDrag();
 441             new Thread(() -> {
 442                 try {
 443                     Thread.sleep(120000);
 444                 } catch (InterruptedException e) {
 445                     e.printStackTrace();
 446                 }
 447                 if (dropCount == 0) {
 448                     if (idt.frame != null) {
 449                         idt.frame.dispose();
 450                     }
 451                     System.exit(1);
 452                 }
 453             }).start();
 454         } catch (Throwable e) {
 455             if (idt.frame != null) {
 456                 idt.frame.dispose();
 457             }
 458             e.printStackTrace();
 459             System.exit(1);
 460         }
 461     }
 462 
 463 }
 464 
 465 
 466 class ImageSelection implements Transferable {
 467     private static final int IMAGE = 0;
 468     private static final DataFlavor[] flavors = {DataFlavor.imageFlavor};
 469     private Image data;
 470 
 471     public ImageSelection(Image data) {
 472         this.data = data;
 473     }
 474 
 475     @Override
 476     public DataFlavor[] getTransferDataFlavors() {
 477         // returning flavors itself would allow client code to modify
 478         // our internal behavior
 479         return flavors.clone();
 480     }
 481 
 482     @Override
 483     public boolean isDataFlavorSupported(DataFlavor flavor) {
 484         return Stream.of(flavor).anyMatch(flavor::equals);
 485     }
 486 
 487     @Override
 488     public Object getTransferData(DataFlavor flavor)
 489             throws UnsupportedFlavorException
 490     {
 491         if (flavor.equals(flavors[IMAGE])) {
 492             return data;
 493         } else {
 494             throw new UnsupportedFlavorException(flavor);
 495         }
 496     }
 497 }
 498 
--- EOF ---