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 #import "CClipboard.h"
  27 #import "CDataTransferer.h"
  28 #import "ThreadUtilities.h"
  29 #import "jni_util.h" 
  30 #import <Cocoa/Cocoa.h>
  31 #import <JavaNativeFoundation/JavaNativeFoundation.h>
  32 
  33 static CClipboard *sClipboard = nil;
  34 
  35 //
  36 // CClipboardUpdate is used for mulitple calls to setData that happen before
  37 // the model and AppKit can get back in sync.
  38 //
  39 
  40 @interface CClipboardUpdate : NSObject {
  41     NSData *fData;
  42     NSString *fFormat;
  43 }
  44 
  45 - (id)initWithData:(NSData *)inData withFormat:(NSString *)inFormat;
  46 - (NSData *)data;
  47 - (NSString *)format;
  48 
  49 @end
  50 
  51 @implementation CClipboardUpdate
  52 
  53 - (id)initWithData:(NSData *)inData withFormat:(NSString *)inFormat
  54 {
  55     self = [super init];
  56 
  57     if (self != nil) {
  58         fData = [inData retain];
  59         fFormat = [inFormat retain];
  60     }
  61 
  62     return self;
  63 }
  64 
  65 - (void)dealloc
  66 {
  67     [fData release];
  68     fData = nil;
  69 
  70     [fFormat release];
  71     fFormat = nil;
  72 
  73     [super dealloc];
  74 }
  75 //- (void)finalize { [super finalize]; }
  76 
  77 - (NSData *)data {
  78     return fData;
  79 }
  80 
  81 - (NSString *)format {
  82     return fFormat;
  83 }
  84 @end
  85 
  86 @implementation CClipboard
  87 
  88 // Clipboard creation is synchronized at the Java level.
  89 + (CClipboard *) sharedClipboard
  90 {
  91     if (sClipboard == nil) {
  92         sClipboard = [[CClipboard alloc] init];
  93         [[NSNotificationCenter defaultCenter] addObserver:sClipboard selector: @selector(checkPasteboard:)
  94                                                      name: NSApplicationDidBecomeActiveNotification
  95                                                    object: nil];
  96     }
  97 
  98     return sClipboard;
  99 }
 100 
 101 - (id) init
 102 {
 103     self = [super init];
 104 
 105     if (self != nil) {
 106         fChangeCount = [[NSPasteboard generalPasteboard] changeCount];
 107     }
 108 
 109     return self;
 110 }
 111 
 112 - (void) javaDeclareTypes:(NSArray *)inTypes withOwner:(jobject)inClipboard jniEnv:(JNIEnv *)inEnv {
 113 
 114     @synchronized(self) {
 115         if (inClipboard != NULL) {
 116             if (fClipboardOwner != NULL) {
 117                 JNFDeleteGlobalRef(inEnv, fClipboardOwner);
 118             }
 119             fClipboardOwner = JNFNewGlobalRef(inEnv, inClipboard);
 120         }
 121     }
 122     [ThreadUtilities performOnMainThread:@selector(_nativeDeclareTypes:) on:self withObject:inTypes waitUntilDone:YES];
 123 }
 124 
 125 - (void) _nativeDeclareTypes:(NSArray *)inTypes {
 126     AWT_ASSERT_APPKIT_THREAD;
 127 
 128     fChangeCount = [[NSPasteboard generalPasteboard] declareTypes:inTypes owner:self];
 129 }
 130 
 131 
 132 - (NSArray *) javaGetTypes {
 133 
 134     NSMutableArray *args = [NSMutableArray arrayWithCapacity:1];
 135     [ThreadUtilities performOnMainThread:@selector(_nativeGetTypes:) on:self withObject:args waitUntilDone:YES];
 136     return [args lastObject];
 137 }
 138 
 139 - (void) _nativeGetTypes:(NSMutableArray *)args {
 140     AWT_ASSERT_APPKIT_THREAD;
 141 
 142     [args addObject:[[NSPasteboard generalPasteboard] types]];
 143 }
 144 
 145 - (void) javaSetData:(NSData *)inData forType:(NSString *) inFormat {
 146 
 147     CClipboardUpdate *newUpdate = [[CClipboardUpdate alloc] initWithData:inData withFormat:inFormat];
 148     [ThreadUtilities performOnMainThread:@selector(_nativeSetData:) on:self withObject:newUpdate waitUntilDone:YES];
 149     [newUpdate release];
 150 }
 151 
 152 - (void) _nativeSetData:(CClipboardUpdate *)newUpdate {
 153     AWT_ASSERT_APPKIT_THREAD;
 154 
 155     [[NSPasteboard generalPasteboard] setData:[newUpdate data] forType:[newUpdate format]];
 156 }
 157 
 158 - (NSData *) javaGetDataForType:(NSString *) inFormat {
 159 
 160     NSMutableArray *args = [NSMutableArray arrayWithObject:inFormat];
 161     [ThreadUtilities performOnMainThread:@selector(_nativeGetDataForType:) on:self withObject:args waitUntilDone:YES];
 162     return [args lastObject];
 163 }
 164 
 165 - (void) _nativeGetDataForType:(NSMutableArray *) args {
 166     AWT_ASSERT_APPKIT_THREAD;
 167 
 168     NSData *returnValue = [[NSPasteboard generalPasteboard] dataForType:[args objectAtIndex:0]];
 169 
 170     if (returnValue) [args replaceObjectAtIndex:0 withObject:returnValue];
 171     else [args removeLastObject];
 172 }
 173 
 174 - (void) checkPasteboard:(id)application {
 175     AWT_ASSERT_APPKIT_THREAD;
 176     
 177     // This is called via NSApplicationDidBecomeActiveNotification.
 178     
 179     // If the change count on the general pasteboard is different than when we set it
 180     // someone else put data on the clipboard.  That means the current owner lost ownership.
 181     NSInteger newChangeCount = [[NSPasteboard generalPasteboard] changeCount];
 182     
 183     if (fChangeCount != newChangeCount) {
 184         fChangeCount = newChangeCount;    
 185 
 186         // Notify that the content might be changed
 187         static JNF_CLASS_CACHE(jc_CClipboard, "sun/lwawt/macosx/CClipboard");
 188         static JNF_STATIC_MEMBER_CACHE(jm_contentChanged, jc_CClipboard, "notifyChanged", "()V");
 189         JNIEnv *env = [ThreadUtilities getJNIEnv];
 190         JNFCallStaticVoidMethod(env, jm_contentChanged);
 191 
 192         // If we have a Java pasteboard owner, tell it that it doesn't own the pasteboard anymore.
 193         static JNF_MEMBER_CACHE(jm_lostOwnership, jc_CClipboard, "notifyLostOwnership", "()V");
 194         @synchronized(self) {
 195             if (fClipboardOwner) {
 196                 JNIEnv *env = [ThreadUtilities getJNIEnv];
 197                 JNFCallVoidMethod(env, fClipboardOwner, jm_lostOwnership); // AWT_THREADING Safe (event)
 198                 JNFDeleteGlobalRef(env, fClipboardOwner);
 199                 fClipboardOwner = NULL;
 200             }
 201         }
 202     }
 203 }
 204 
 205 @end
 206 
 207 /*
 208  * Class:     sun_lwawt_macosx_CClipboard
 209  * Method:    declareTypes
 210  * Signature: ([JLsun/awt/datatransfer/SunClipboard;)V
 211 */
 212 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CClipboard_declareTypes
 213 (JNIEnv *env, jobject inObject, jlongArray inTypes, jobject inJavaClip)
 214 {
 215 JNF_COCOA_ENTER(env);
 216 
 217     jint i;
 218     jint nElements = (*env)->GetArrayLength(env, inTypes);
 219     NSMutableArray *formatArray = [NSMutableArray arrayWithCapacity:nElements];
 220     jlong *elements = (*env)->GetPrimitiveArrayCritical(env, inTypes, NULL);
 221 
 222     for (i = 0; i < nElements; i++) {
 223         NSString *pbFormat = formatForIndex(elements[i]);
 224         if (pbFormat)
 225             [formatArray addObject:pbFormat];
 226     }
 227 
 228     (*env)->ReleasePrimitiveArrayCritical(env, inTypes, elements, JNI_ABORT);
 229     [[CClipboard sharedClipboard] javaDeclareTypes:formatArray withOwner:inJavaClip jniEnv:env];
 230 JNF_COCOA_EXIT(env);
 231 }
 232 
 233 /*
 234  * Class:     sun_lwawt_macosx_CClipboard
 235  * Method:    setData
 236  * Signature: ([BJ)V
 237 */
 238 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CClipboard_setData
 239 (JNIEnv *env, jobject inObject, jbyteArray inBytes, jlong inFormat)
 240 {
 241     if (inBytes == NULL) {
 242         return;
 243     }
 244 
 245 JNF_COCOA_ENTER(env);
 246     jint nBytes = (*env)->GetArrayLength(env, inBytes);
 247     jbyte *rawBytes = (*env)->GetPrimitiveArrayCritical(env, inBytes, NULL);
 248     CHECK_NULL(rawBytes);
 249     NSData *bytesAsData = [NSData dataWithBytes:rawBytes length:nBytes];
 250     (*env)->ReleasePrimitiveArrayCritical(env, inBytes, rawBytes, JNI_ABORT);
 251     NSString *format = formatForIndex(inFormat);
 252     [[CClipboard sharedClipboard] javaSetData:bytesAsData forType:format];
 253 JNF_COCOA_EXIT(env);
 254 }
 255 
 256 /*
 257  * Class:     sun_lwawt_macosx_CClipboard
 258  * Method:    getClipboardFormats
 259  * Signature: (J)[J
 260      */
 261 JNIEXPORT jlongArray JNICALL Java_sun_lwawt_macosx_CClipboard_getClipboardFormats
 262 (JNIEnv *env, jobject inObject)
 263 {
 264     jlongArray returnValue = NULL;
 265 JNF_COCOA_ENTER(env);
 266 
 267     NSArray *dataTypes = [[CClipboard sharedClipboard] javaGetTypes];
 268     NSUInteger nFormats = [dataTypes count];
 269     NSUInteger knownFormats = 0;
 270     NSUInteger i;
 271 
 272     // There can be any number of formats on the general pasteboard.  Find out which ones
 273     // we know about (i.e., live in the flavormap.properties).
 274     for (i = 0; i < nFormats; i++) {
 275         NSString *format = (NSString *)[dataTypes objectAtIndex:i];
 276         if (indexForFormat(format) != -1)
 277             knownFormats++;
 278     }
 279 
 280     returnValue = (*env)->NewLongArray(env, knownFormats);
 281     if (returnValue == NULL) {
 282         return NULL;
 283     }
 284 
 285     if (knownFormats == 0) {
 286         return returnValue;
 287     }
 288 
 289     // Now go back and map the formats we found back to Java indexes.
 290     jboolean isCopy;
 291     jlong *lFormats = (*env)->GetLongArrayElements(env, returnValue, &isCopy);
 292     jlong *saveFormats = lFormats;
 293 
 294     for (i = 0; i < nFormats; i++) {
 295         NSString *format = (NSString *)[dataTypes objectAtIndex:i];
 296         jlong index = indexForFormat(format);
 297 
 298         if (index != -1) {
 299             *lFormats = index;
 300             lFormats++;
 301         }
 302     }
 303 
 304     (*env)->ReleaseLongArrayElements(env, returnValue, saveFormats, JNI_COMMIT);
 305 JNF_COCOA_EXIT(env);
 306     return returnValue;
 307 }
 308 
 309 /*
 310  * Class:     sun_lwawt_macosx_CClipboard
 311  * Method:    getClipboardData
 312  * Signature: (JJ)[B
 313      */
 314 JNIEXPORT jbyteArray JNICALL Java_sun_lwawt_macosx_CClipboard_getClipboardData
 315 (JNIEnv *env, jobject inObject, jlong format)
 316 {
 317     jbyteArray returnValue = NULL;
 318 
 319     // Note that this routine makes no attempt to interpret the data, since we're returning
 320     // a byte array back to Java.  CDataTransferer will do that if necessary.
 321 JNF_COCOA_ENTER(env);
 322 
 323     NSString *formatAsString = formatForIndex(format);
 324     NSData *clipData = [[CClipboard sharedClipboard] javaGetDataForType:formatAsString];
 325 
 326     if (clipData == NULL) {
 327         [JNFException raise:env as:"java/io/IOException" reason:"Font transform has NaN position"];
 328         return NULL;
 329     }
 330 
 331     NSUInteger dataSize = [clipData length];
 332     returnValue = (*env)->NewByteArray(env, dataSize);
 333     if (returnValue == NULL) {
 334         return NULL;
 335     }
 336 
 337     if (dataSize != 0) {
 338         const void *dataBuffer = [clipData bytes];
 339         (*env)->SetByteArrayRegion(env, returnValue, 0, dataSize, (jbyte *)dataBuffer);
 340     }
 341 
 342 JNF_COCOA_EXIT(env);
 343     return returnValue;
 344 }
 345 
 346 /*
 347  * Class:     sun_lwawt_macosx_CClipboard
 348  * Method:    checkPasteboard
 349  * Signature: ()V
 350  */
 351 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CClipboard_checkPasteboard
 352 (JNIEnv *env, jobject inObject )
 353 {
 354     JNF_COCOA_ENTER(env);
 355 
 356     [ThreadUtilities performOnMainThreadWaiting:YES block:^(){
 357         [[CClipboard sharedClipboard] checkPasteboard:nil];
 358     }];
 359         
 360     JNF_COCOA_EXIT(env);
 361 }
 362 
 363