1 /*
   2  * Copyright (c) 2011, 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.  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.lwawt.macosx;
  27 
  28 import java.awt.*;
  29 import java.awt.image.*;
  30 import sun.awt.image.ImageRepresentation;
  31 
  32 import java.io.*;
  33 import java.net.URL;
  34 import java.text.Normalizer;
  35 import java.text.Normalizer.Form;
  36 import java.util.*;
  37 
  38 import java.awt.datatransfer.*;
  39 import sun.awt.datatransfer.*;
  40 
  41 public class CDataTransferer extends DataTransferer {
  42     private static final Map<String, Long> predefinedClipboardNameMap;
  43     private static final Map<Long, String> predefinedClipboardFormatMap;
  44 
  45     // See SystemFlavorMap, or the flavormap.properties file:
  46     // We should define a few more types in flavormap.properties, it's rather slim now.
  47     private static final String[] predefinedClipboardNames = {
  48         "",
  49         "STRING",
  50         "FILE_NAME",
  51         "TIFF",
  52         "RICH_TEXT",
  53         "HTML",
  54         "PDF",
  55         "URL",
  56         "PNG",
  57         "JFIF"
  58     };
  59 
  60     static {
  61         Map<String, Long> nameMap = new HashMap<>(predefinedClipboardNames.length, 1.0f);
  62         Map<Long, String> formatMap = new HashMap<>(predefinedClipboardNames.length, 1.0f);
  63         for (int i = 1; i < predefinedClipboardNames.length; i++) {
  64             nameMap.put(predefinedClipboardNames[i], (long) i);
  65             formatMap.put((long) i, predefinedClipboardNames[i]);
  66         }
  67         predefinedClipboardNameMap = Collections.synchronizedMap(nameMap);
  68         predefinedClipboardFormatMap = Collections.synchronizedMap(formatMap);
  69     }
  70 
  71     public static final int CF_UNSUPPORTED = 0;
  72     public static final int CF_STRING      = 1;
  73     public static final int CF_FILE        = 2;
  74     public static final int CF_TIFF        = 3;
  75     public static final int CF_RICH_TEXT   = 4;
  76     public static final int CF_HTML        = 5;
  77     public static final int CF_PDF         = 6;
  78     public static final int CF_URL         = 7;
  79     public static final int CF_PNG         = 8;
  80     public static final int CF_JPEG        = 9;
  81 
  82     private CDataTransferer() {}
  83 
  84     private static CDataTransferer fTransferer;
  85 
  86     static synchronized CDataTransferer getInstanceImpl() {
  87         if (fTransferer == null) {
  88             fTransferer = new CDataTransferer();
  89         }
  90 
  91         return fTransferer;
  92     }
  93 
  94     @Override
  95     public String getDefaultUnicodeEncoding() {
  96         return "utf-16le";
  97     }
  98 
  99     @Override
 100     public boolean isLocaleDependentTextFormat(long format) {
 101         return format == CF_STRING;
 102     }
 103 
 104     @Override
 105     public boolean isFileFormat(long format) {
 106         return format == CF_FILE;
 107     }
 108 
 109     @Override
 110     public boolean isImageFormat(long format) {
 111         int ifmt = (int)format;
 112         switch(ifmt) {
 113             case CF_TIFF:
 114             case CF_PDF:
 115             case CF_PNG:
 116             case CF_JPEG:
 117                 return true;
 118             default:
 119                 return false;
 120         }
 121     }
 122 
 123     @Override
 124     public Object translateBytes(byte[] bytes, DataFlavor flavor,
 125                                     long format, Transferable transferable) throws IOException {
 126 
 127             if (format == CF_URL && URL.class.equals(flavor.getRepresentationClass()))
 128             {
 129                 String charset = getDefaultTextCharset();
 130                 if (transferable != null && transferable.isDataFlavorSupported(javaTextEncodingFlavor)) {
 131                     try {
 132                         charset = new String((byte[])transferable.getTransferData(javaTextEncodingFlavor), "UTF-8");
 133                     } catch (UnsupportedFlavorException cannotHappen) {
 134                     }
 135                 }
 136 
 137                 return new URL(new String(bytes, charset));
 138             }
 139 
 140             if (format == CF_STRING) {
 141                 bytes = Normalizer.normalize(new String(bytes, "UTF8"), Form.NFC).getBytes("UTF8");
 142             }
 143 
 144             return super.translateBytes(bytes, flavor, format, transferable);
 145     }
 146 
 147     @Override
 148     synchronized protected Long getFormatForNativeAsLong(String str) {
 149         Long format = predefinedClipboardNameMap.get(str);
 150 
 151         if (format == null) {
 152             if (java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().isHeadlessInstance()) {
 153                 // Do not try to access native system for the unknown format
 154                 return -1L;
 155             }
 156             format = registerFormatWithPasteboard(str);
 157             predefinedClipboardNameMap.put(str, format);
 158             predefinedClipboardFormatMap.put(format, str);
 159         }
 160 
 161         return format;
 162     }
 163 
 164     /*
 165      * Adds type to native mapping NSDictionary.
 166      */
 167     private native long registerFormatWithPasteboard(String type);
 168 
 169     // Get registered native format string for an index, return null if unknown:
 170     private native String formatForIndex(long index);
 171 
 172     @Override
 173     protected String getNativeForFormat(long format) {
 174         String returnValue = null;
 175 
 176         // The most common case - just index the array of predefined names:
 177         if (format >= 0 && format < predefinedClipboardNames.length) {
 178             returnValue = predefinedClipboardNames[(int) format];
 179         } else {
 180             Long formatObj = format;
 181             returnValue = predefinedClipboardFormatMap.get(formatObj);
 182 
 183             // predefinedClipboardFormatMap may not know this format:
 184             if (returnValue == null) {
 185                 returnValue = formatForIndex(format);
 186 
 187                 // Native clipboard may not know this format either:
 188                 if (returnValue != null) {
 189                     predefinedClipboardNameMap.put(returnValue, formatObj);
 190                     predefinedClipboardFormatMap.put(formatObj, returnValue);
 191                 }
 192             }
 193         }
 194 
 195         if (returnValue == null) {
 196             returnValue = predefinedClipboardNames[CF_UNSUPPORTED];
 197         }
 198 
 199         return returnValue;
 200     }
 201 
 202     private final ToolkitThreadBlockedHandler handler = new CToolkitThreadBlockedHandler();
 203 
 204     @Override
 205     public ToolkitThreadBlockedHandler getToolkitThreadBlockedHandler() {
 206         return handler;
 207     }
 208 
 209     private native byte[] imageDataToPlatformImageBytes(int[] rData, int nW, int nH);
 210     @Override
 211     protected byte[] imageToPlatformBytes(Image image, long format) {
 212         int w = image.getWidth(null);
 213         int h = image.getHeight(null);
 214         BufferedImage bimage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB_PRE);
 215         Graphics g = bimage.getGraphics();
 216         g.drawImage(image, 0, 0, w, h, null);
 217         g.dispose();
 218         Raster raster = bimage.getRaster();
 219         DataBuffer buffer = raster.getDataBuffer();
 220         return imageDataToPlatformImageBytes(((DataBufferInt)buffer).getData(),
 221                                              raster.getWidth(),
 222                                              raster.getHeight());
 223     }
 224 
 225     private static native String[] nativeDragQueryFile(final byte[] bytes);
 226     @Override
 227     protected String[] dragQueryFile(final byte[] bytes) {
 228         if (bytes == null) return null;
 229         if (new String(bytes).startsWith("Unsupported type")) return null;
 230         return nativeDragQueryFile(bytes);
 231     }
 232 
 233     private native Image getImageForByteStream(byte[] bytes);
 234     /**
 235      * Translates a byte array which contains
 236      * platform-specific image data in the given format into an Image.
 237      */
 238     @Override
 239     protected Image platformImageBytesToImage(byte[] bytes, long format) throws IOException {
 240         return getImageForByteStream(bytes);
 241     }
 242 
 243     @Override
 244     protected ByteArrayOutputStream convertFileListToBytes(ArrayList<String> fileList) throws IOException {
 245         ByteArrayOutputStream bos = new ByteArrayOutputStream();
 246         for (String file : fileList) {
 247             byte[] bytes = file.getBytes();
 248             bos.write(bytes, 0, bytes.length);
 249             bos.write(0);
 250         }
 251         return bos;
 252     }
 253 
 254     @Override
 255     protected boolean isURIListFormat(long format) {
 256         String nat = getNativeForFormat(format);
 257         if (nat == null) {
 258             return false;
 259         }
 260         try {
 261             DataFlavor df = new DataFlavor(nat);
 262             if (df.getPrimaryType().equals("text") && df.getSubType().equals("uri-list")) {
 263                 return true;
 264             }
 265         } catch (Exception e) {
 266             // Not a MIME format.
 267         }
 268         return false;
 269     }
 270 }
 271 
 272