jdk/src/macosx/native/sun/awt/CDataTransferer.m
changeset 12047 320a714614e9
child 23010 6dadb192ad81
child 23303 a88030d506db
equal deleted inserted replaced
12046:378aa3362868 12047:320a714614e9
       
     1 /*
       
     2  * Copyright (c) 2011, 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 #import "CDataTransferer.h"
       
    27 #include "sun_lwawt_macosx_CDataTransferer.h"
       
    28 
       
    29 #import <AppKit/AppKit.h>
       
    30 #import <JavaNativeFoundation/JavaNativeFoundation.h>
       
    31 
       
    32 #include "ThreadUtilities.h"
       
    33 
       
    34 
       
    35 // ***** NOTE ***** This dictionary corresponds to the static array predefinedClipboardNames
       
    36 // in CDataTransferer.java.
       
    37 NSMutableDictionary *sStandardMappings = nil;
       
    38 
       
    39 NSMutableDictionary *getMappingTable() {
       
    40     if (sStandardMappings == nil) {
       
    41         sStandardMappings = [[NSMutableDictionary alloc] init];
       
    42         [sStandardMappings setObject:NSStringPboardType
       
    43                               forKey:[NSNumber numberWithLong:sun_lwawt_macosx_CDataTransferer_CF_STRING]];
       
    44         [sStandardMappings setObject:NSFilenamesPboardType
       
    45                               forKey:[NSNumber numberWithLong:sun_lwawt_macosx_CDataTransferer_CF_FILE]];
       
    46         [sStandardMappings setObject:NSTIFFPboardType
       
    47                               forKey:[NSNumber numberWithLong:sun_lwawt_macosx_CDataTransferer_CF_TIFF]];
       
    48         [sStandardMappings setObject:NSRTFPboardType
       
    49                               forKey:[NSNumber numberWithLong:sun_lwawt_macosx_CDataTransferer_CF_RICH_TEXT]];
       
    50         [sStandardMappings setObject:NSHTMLPboardType
       
    51                               forKey:[NSNumber numberWithLong:sun_lwawt_macosx_CDataTransferer_CF_HTML]];
       
    52         [sStandardMappings setObject:NSPDFPboardType
       
    53                               forKey:[NSNumber numberWithLong:sun_lwawt_macosx_CDataTransferer_CF_PDF]];
       
    54         [sStandardMappings setObject:NSURLPboardType
       
    55                               forKey:[NSNumber numberWithLong:sun_lwawt_macosx_CDataTransferer_CF_URL]];
       
    56     }
       
    57     return sStandardMappings;
       
    58 }
       
    59 
       
    60 /*
       
    61  * Convert from a standard NSPasteboard data type to an index in our mapping table.
       
    62  */
       
    63 jlong indexForFormat(NSString *format) {
       
    64     jlong returnValue = -1;
       
    65 
       
    66     NSMutableDictionary *mappingTable = getMappingTable();
       
    67     NSArray *matchingKeys = [mappingTable allKeysForObject:format];
       
    68 
       
    69     // There should only be one matching key here...
       
    70     if ([matchingKeys count] > 0) {
       
    71         NSNumber *formatID = (NSNumber *)[matchingKeys objectAtIndex:0];
       
    72         returnValue = [formatID longValue];
       
    73     }
       
    74 
       
    75     // If we don't recognize the format, but it's a Java "custom" format register it
       
    76     if (returnValue == -1 && ([format hasPrefix:@"JAVA_DATAFLAVOR:"]) ) {
       
    77         returnValue = registerFormatWithPasteboard(format);
       
    78     }
       
    79 
       
    80     return returnValue;
       
    81 }
       
    82 
       
    83 /*
       
    84  * Inverse of above -- given a long int index, get the matching data format NSString.
       
    85  */
       
    86 NSString *formatForIndex(jlong inFormatCode) {
       
    87     return [getMappingTable() objectForKey:[NSNumber numberWithLong:inFormatCode]];
       
    88 }
       
    89 
       
    90 jlong registerFormatWithPasteboard(NSString *format) {
       
    91     NSMutableDictionary *mappingTable = getMappingTable();
       
    92     NSUInteger nextID = [mappingTable count] + 1;
       
    93     [mappingTable setObject:format forKey:[NSNumber numberWithLong:nextID]];
       
    94     return nextID;
       
    95 }
       
    96 
       
    97 
       
    98 /*
       
    99  * Class:     sun_lwawt_macosx_CDataTransferer
       
   100  * Method:    registerFormatWithPasteboard
       
   101  * Signature: (Ljava/lang/String;)J
       
   102  */
       
   103 JNIEXPORT jlong JNICALL Java_sun_lwawt_macosx_CDataTransferer_registerFormatWithPasteboard
       
   104 (JNIEnv *env, jobject jthis, jstring newformat)
       
   105 {
       
   106     jlong returnValue = -1;
       
   107 JNF_COCOA_ENTER(env);
       
   108     returnValue = registerFormatWithPasteboard(JNFJavaToNSString(env, newformat));
       
   109 JNF_COCOA_EXIT(env);
       
   110     return returnValue;
       
   111 }
       
   112 
       
   113 /*
       
   114  * Class:     sun_lwawt_macosx_CDataTransferer
       
   115  * Method:    formatForIndex
       
   116  * Signature: (J)Ljava/lang/String;
       
   117  */
       
   118 JNIEXPORT jstring JNICALL Java_sun_lwawt_macosx_CDataTransferer_formatForIndex
       
   119   (JNIEnv *env, jobject jthis, jlong index)
       
   120 {
       
   121     jstring returnValue = NULL;
       
   122 JNF_COCOA_ENTER(env);
       
   123     returnValue = JNFNSToJavaString(env, formatForIndex(index));
       
   124 JNF_COCOA_EXIT(env);
       
   125     return returnValue;
       
   126 }
       
   127 
       
   128 /*
       
   129  * Class:     sun_lwawt_macosx_CDataTransferer
       
   130  * Method:    imageDataToPlatformImageBytes
       
   131  * Signature: ([III)[B
       
   132      */
       
   133 JNIEXPORT jbyteArray JNICALL Java_sun_lwawt_macosx_CDataTransferer_imageDataToPlatformImageBytes
       
   134 (JNIEnv *env, jobject obj, jintArray inPixelData, jint inWidth, jint inHeight)
       
   135 {
       
   136     jbyteArray returnValue = nil;
       
   137 JNF_COCOA_ENTER(env);
       
   138     UInt32 *rawImageData = (UInt32 *)(*env)->GetPrimitiveArrayCritical(env, inPixelData, 0);
       
   139 
       
   140     // The pixel data is in premultiplied ARGB format. That's exactly what
       
   141     // we need for the bitmap image rep.
       
   142     if (rawImageData != NULL) {
       
   143         NSBitmapImageRep *imageRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL
       
   144                                                                              pixelsWide:inWidth
       
   145                                                                              pixelsHigh:inHeight
       
   146                                                                           bitsPerSample:8
       
   147                                                                         samplesPerPixel:4
       
   148                                                                                hasAlpha:YES
       
   149                                                                                isPlanar:NO
       
   150                                                                          colorSpaceName:NSCalibratedRGBColorSpace
       
   151                                                                             bytesPerRow:(inWidth*4)
       
   152                                                                            bitsPerPixel:32];
       
   153 
       
   154         // Conver the ARGB data into RGBA data that the bitmap can draw.
       
   155         unsigned char *destData = [imageRep bitmapData];
       
   156         unsigned char *currentRowBase;
       
   157         jint x, y;
       
   158 
       
   159         for (y = 0; y < inHeight; y++) {
       
   160             currentRowBase = destData + y * (inWidth * 4);
       
   161             unsigned char *currElement = currentRowBase;
       
   162             for (x = 0; x < inWidth; x++) {
       
   163                 UInt32 currPixel = rawImageData[y * inWidth + x];
       
   164                 *currElement++ = ((currPixel & 0xFF0000) >> 16);
       
   165                 *currElement++ = ((currPixel & 0xFF00) >> 8);
       
   166                 *currElement++ = (currPixel & 0xFF);
       
   167                 *currElement++ = ((currPixel & 0xFF000000) >> 24);
       
   168             }
       
   169         }
       
   170 
       
   171         (*env)->ReleasePrimitiveArrayCritical(env, inPixelData, rawImageData, JNI_ABORT);
       
   172         NSData *tiffImage = [imageRep TIFFRepresentation];
       
   173         jsize tiffSize = (jsize)[tiffImage length]; // #warning 64-bit: -length returns NSUInteger, but NewByteArray takes jsize
       
   174         returnValue = (*env)->NewByteArray(env, tiffSize);
       
   175         jbyte *tiffData = (jbyte *)(*env)->GetPrimitiveArrayCritical(env, returnValue, 0);
       
   176         [tiffImage getBytes:tiffData];
       
   177         (*env)->ReleasePrimitiveArrayCritical(env, returnValue, tiffData, 0); // Do not use JNI_COMMIT, as that will not free the buffer copy when +ProtectJavaHeap is on.
       
   178         [imageRep release];
       
   179     }
       
   180 JNF_COCOA_EXIT(env);
       
   181     return returnValue;
       
   182 
       
   183 }
       
   184 
       
   185 static jobject getImageForByteStream(JNIEnv *env, jbyteArray sourceData)
       
   186 {
       
   187     if (sourceData == NULL) return NULL;
       
   188 
       
   189     jsize sourceSize = (*env)->GetArrayLength(env, sourceData);
       
   190     if (sourceSize == 0) return NULL;
       
   191 
       
   192     jbyte *sourceBytes = (*env)->GetPrimitiveArrayCritical(env, sourceData, NULL);
       
   193     NSData *rawData = [NSData dataWithBytes:sourceBytes length:sourceSize];
       
   194 
       
   195     NSImage *newImage = [[NSImage alloc] initWithData:rawData];
       
   196     if (newImage) CFRetain(newImage); // GC
       
   197     [newImage release];
       
   198 
       
   199     (*env)->ReleasePrimitiveArrayCritical(env, sourceData, sourceBytes, JNI_ABORT);
       
   200 
       
   201     if (newImage == nil) return NULL;
       
   202 
       
   203     // The ownership of the NSImage is passed to the new CImage jobject. No need to release it.
       
   204     static JNF_CLASS_CACHE(jc_CImage, "sun/lwawt/macosx/CImage");
       
   205     static JNF_STATIC_MEMBER_CACHE(jm_CImage_getCreator, jc_CImage, "getCreator", "()Lsun/lwawt/macosx/CImage$Creator;");
       
   206     jobject creator = JNFCallStaticObjectMethod(env, jm_CImage_getCreator);
       
   207 
       
   208     static JNF_CLASS_CACHE(jc_CImage_Generator, "sun/lwawt/macosx/CImage$Creator");
       
   209     static JNF_MEMBER_CACHE(jm_CImage_Generator_createImageUsingNativeSize, jc_CImage_Generator, "createImageUsingNativeSize", "(J)Ljava/awt/image/BufferedImage;");
       
   210     return JNFCallObjectMethod(env, creator, jm_CImage_Generator_createImageUsingNativeSize, ptr_to_jlong(newImage)); // AWT_THREADING Safe (known object)
       
   211 }
       
   212 
       
   213 /*
       
   214  * Class:     sun_lwawt_macosx_CDataTransferer
       
   215  * Method:    getImageForByteStream
       
   216  * Signature: ([B)Ljava/awt/Image;
       
   217  */
       
   218 JNIEXPORT jobject JNICALL Java_sun_lwawt_macosx_CDataTransferer_getImageForByteStream
       
   219   (JNIEnv *env, jobject obj, jbyteArray sourceData)
       
   220 {
       
   221     jobject img = NULL;
       
   222 JNF_COCOA_ENTER(env);
       
   223     img = getImageForByteStream(env, sourceData);
       
   224 JNF_COCOA_EXIT(env);
       
   225     return img;
       
   226 }
       
   227 
       
   228 static jobjectArray CreateJavaFilenameArray(JNIEnv *env, NSArray *filenameArray)
       
   229 {
       
   230     NSUInteger filenameCount = [filenameArray count];
       
   231     if (filenameCount == 0) return nil;
       
   232 
       
   233     // Get the java.lang.String class object:
       
   234     jclass stringClazz = (*env)->FindClass(env, "java/lang/String"); // can't be null
       
   235     jobject jfilenameArray = (*env)->NewObjectArray(env, filenameCount, stringClazz, NULL); // AWT_THREADING Safe (known object)
       
   236     if ((*env)->ExceptionOccurred(env)) {
       
   237         (*env)->ExceptionDescribe(env);
       
   238         (*env)->ExceptionClear(env);
       
   239         return nil;
       
   240     }
       
   241     if (!jfilenameArray) {
       
   242         NSLog(@"CDataTransferer_CreateJavaFilenameArray: couldn't create jfilenameArray.");
       
   243         return nil;
       
   244     }
       
   245     (*env)->DeleteLocalRef(env, stringClazz);
       
   246 
       
   247     // Iterate through all the filenames:
       
   248     NSUInteger i;
       
   249     for (i = 0; i < filenameCount; i++) {
       
   250         NSMutableString *stringVal = [[NSMutableString alloc] initWithString:[filenameArray objectAtIndex:i]];
       
   251         CFStringNormalize((CFMutableStringRef)stringVal, kCFStringNormalizationFormC);
       
   252         const char* stringBytes = [stringVal UTF8String];
       
   253 
       
   254         // Create a Java String:
       
   255         jstring string = (*env)->NewStringUTF(env, stringBytes);
       
   256         if ((*env)->ExceptionOccurred(env)) {
       
   257             (*env)->ExceptionDescribe(env);
       
   258             (*env)->ExceptionClear(env);
       
   259             continue;
       
   260         }
       
   261         if (!string) {
       
   262             NSLog(@"CDataTransferer_CreateJavaFilenameArray: couldn't create jstring[%lu] for [%@].", (unsigned long) i, stringVal);
       
   263             continue;
       
   264         }
       
   265 
       
   266         // Set the Java array element with our String:
       
   267         (*env)->SetObjectArrayElement(env, jfilenameArray, i, string);
       
   268         if ((*env)->ExceptionOccurred(env)) {
       
   269             (*env)->ExceptionDescribe(env);
       
   270             (*env)->ExceptionClear(env);
       
   271             continue;
       
   272         }
       
   273 
       
   274         // Release local String reference:
       
   275         (*env)->DeleteLocalRef(env, string);
       
   276     }
       
   277 
       
   278     return jfilenameArray;
       
   279 }
       
   280 
       
   281 /*
       
   282  * Class:     sun_lwawt_macosx_CDataTransferer
       
   283  * Method:    draqQueryFile
       
   284  * Signature: ([B)[Ljava/lang/String;
       
   285  */
       
   286 JNIEXPORT jobjectArray JNICALL
       
   287 Java_sun_lwawt_macosx_CDataTransferer_nativeDragQueryFile
       
   288 (JNIEnv *env, jclass clazz, jbyteArray jbytearray)
       
   289 {
       
   290     // Decodes a byte array into a set of String filenames.
       
   291     // bytes here is an XML property list containing all of the filenames in the drag.
       
   292     // Parse the XML list into strings and return an array of Java strings matching all of the
       
   293     // files in the list.
       
   294 
       
   295     jobjectArray jreturnArray = NULL;
       
   296 
       
   297 JNF_COCOA_ENTER(env);
       
   298     // Get byte array elements:
       
   299     jboolean isCopy;
       
   300     jbyte* jbytes = (*env)->GetByteArrayElements(env, jbytearray, &isCopy);
       
   301     if (jbytes == NULL) {
       
   302         return NULL;
       
   303     }
       
   304 
       
   305     // Wrap jbytes in an NSData object:
       
   306     jsize jbytesLength = (*env)->GetArrayLength(env, jbytearray);
       
   307     NSData *xmlData = [NSData dataWithBytesNoCopy:jbytes length:jbytesLength freeWhenDone:NO];
       
   308 
       
   309     // Create a property list from the Java data:
       
   310     NSString *errString = nil;
       
   311     NSPropertyListFormat plistFormat = 0;
       
   312     id plist = [NSPropertyListSerialization propertyListFromData:xmlData mutabilityOption:NSPropertyListImmutable
       
   313         format:&plistFormat errorDescription:&errString];
       
   314 
       
   315     // The property list must be an array of strings:
       
   316     if (plist == nil || [plist isKindOfClass:[NSArray class]] == FALSE) {
       
   317         NSLog(@"CDataTransferer_dragQueryFile: plist not a valid NSArray (error %@):\n%@", errString, plist);
       
   318         (*env)->ReleaseByteArrayElements(env, jbytearray, jbytes, JNI_ABORT);
       
   319         return NULL;
       
   320     }
       
   321 
       
   322     // Transfer all string items from the plistArray to filenameArray. This wouldn't be necessary
       
   323     // if we could trust the array to contain all valid elements but this way we'll be sure.
       
   324     NSArray *plistArray = (NSArray *)plist;
       
   325     NSUInteger plistItemCount = [plistArray count];
       
   326     NSMutableArray *filenameArray = [[NSMutableArray alloc] initWithCapacity:plistItemCount];
       
   327 
       
   328     NSUInteger i;
       
   329     for (i = 0; i < plistItemCount; i++) {
       
   330         // Filenames must be strings:
       
   331         id idVal = [plistArray objectAtIndex:i];
       
   332         if ([idVal isKindOfClass:[NSString class]] == FALSE) {
       
   333             NSLog(@"CDataTransferer_dragQueryFile: plist[%lu] not an NSString:\n%@", (unsigned long) i, idVal);
       
   334             continue;
       
   335         }
       
   336 
       
   337         [filenameArray addObject:idVal];
       
   338     }
       
   339 
       
   340     // Convert our array of filenames into a Java array of String filenames:
       
   341     jreturnArray = CreateJavaFilenameArray(env, filenameArray);
       
   342 
       
   343     [filenameArray release];
       
   344 
       
   345     // We're done with the jbytes (backing the plist/plistArray):
       
   346     (*env)->ReleaseByteArrayElements(env, jbytearray, jbytes, JNI_ABORT);
       
   347 JNF_COCOA_EXIT(env);
       
   348     return jreturnArray;
       
   349 }