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 //#define DND_DEBUG TRUE
  27 
  28 #import "java_awt_dnd_DnDConstants.h"
  29 
  30 #import <Cocoa/Cocoa.h>
  31 #import <JavaNativeFoundation/JavaNativeFoundation.h>
  32 
  33 #import "AWTEvent.h"
  34 #import "AWTView.h"
  35 #import "CDataTransferer.h"
  36 #import "CDropTarget.h"
  37 #import "CDragSource.h"
  38 #import "DnDUtilities.h"
  39 #import "ThreadUtilities.h"
  40 
  41 
  42 // When sIsJavaDragging is true Java drag gesture has been recognized and a drag is/has been initialized.
  43 // We must stop posting MouseEvent.MOUSE_DRAGGED events for the duration of the drag or all hell will break
  44 // loose in shared code - tracking state going haywire.
  45 static BOOL sIsJavaDragging;
  46 
  47 
  48 @interface NSEvent(AWTAdditions)
  49 
  50 + (void)javaDraggingBegin;
  51 + (void)javaDraggingEnd;
  52 
  53 @end
  54 
  55 
  56 @implementation NSEvent(AWTAdditions)
  57 
  58 
  59 + (void)javaDraggingBegin
  60 {
  61     sIsJavaDragging = YES;
  62 }
  63 
  64 + (void)javaDraggingEnd
  65 {
  66     // sIsJavaDragging is reset on mouseDown as well.
  67     sIsJavaDragging = NO;
  68 }
  69 @end
  70 
  71 JNF_CLASS_CACHE(DataTransfererClass, "sun/awt/datatransfer/DataTransferer");
  72 JNF_CLASS_CACHE(CDragSourceContextPeerClass, "sun/lwawt/macosx/CDragSourceContextPeer");
  73 JNF_CLASS_CACHE(CImageClass, "sun/lwawt/macosx/CImage");
  74 
  75 static NSDragOperation    sDragOperation;
  76 static NSPoint            sDraggingLocation;
  77 
  78 static BOOL                sNeedsEnter;
  79 
  80 @interface CDragSource ()
  81 // Updates from the destination to the source
  82 - (void) postDragEnter;
  83 - (void) postDragExit;
  84 // Utility
  85 - (NSPoint) mapNSScreenPointToJavaWithOffset:(NSPoint) point;
  86 @end
  87 
  88 @implementation CDragSource
  89 
  90 - (id)        init:(jobject)jDragSourceContextPeer
  91          component:(jobject)jComponent
  92            control:(id)control
  93       transferable:(jobject)jTransferable
  94       triggerEvent:(jobject)jTrigger
  95           dragPosX:(jint)dragPosX
  96           dragPosY:(jint)dragPosY
  97          modifiers:(jint)extModifiers
  98         clickCount:(jint)clickCount
  99          timeStamp:(jlong)timeStamp
 100          dragImage:(jobject)jDragImage
 101   dragImageOffsetX:(jint)jDragImageOffsetX
 102   dragImageOffsetY:(jint)jDragImageOffsetY
 103      sourceActions:(jint)jSourceActions
 104            formats:(jlongArray)jFormats
 105          formatMap:(jobject)jFormatMap
 106 {
 107     self = [super init];
 108     DLog2(@"[CDragSource init]: %@\n", self);
 109 
 110     fView = nil;
 111     fComponent = nil;
 112 
 113     // Construct the object if we have a valid model for it:
 114     if (control != nil) {
 115         JNIEnv *env = [ThreadUtilities getJNIEnv];
 116         fComponent = JNFNewGlobalRef(env, jComponent);
 117         fDragSourceContextPeer = JNFNewGlobalRef(env, jDragSourceContextPeer);
 118 
 119         fTransferable = JNFNewGlobalRef(env, jTransferable);
 120         fTriggerEvent = JNFNewGlobalRef(env, jTrigger);
 121 
 122         if (jDragImage) {
 123             JNF_MEMBER_CACHE(nsImagePtr, CImageClass, "ptr", "J");
 124             jlong imgPtr = JNFGetLongField(env, jDragImage, nsImagePtr);
 125             fDragImage = (NSImage*) jlong_to_ptr(imgPtr); // Double-casting prevents compiler 'd$|//
 126 
 127             [fDragImage retain];
 128         }
 129 
 130         fDragImageOffset = NSMakePoint(jDragImageOffsetX, jDragImageOffsetY);
 131 
 132         fSourceActions = jSourceActions;
 133         fFormats = JNFNewGlobalRef(env, jFormats);
 134         fFormatMap = JNFNewGlobalRef(env, jFormatMap);
 135 
 136         fTriggerEventTimeStamp = timeStamp;
 137         fDragPos = NSMakePoint(dragPosX, dragPosY);
 138         fClickCount = clickCount;
 139         fModifiers = extModifiers;
 140 
 141         // Set this object as a dragging source:
 142 
 143         fView = [(AWTView *) control retain];
 144         [fView setDragSource:self];
 145 
 146         // Let AWTEvent know Java drag is getting underway:
 147         [NSEvent javaDraggingBegin];
 148     }
 149 
 150     else {
 151         [self release];
 152         self = nil;
 153     }
 154 
 155     return self;
 156 }
 157 
 158 - (void)removeFromView:(JNIEnv *)env
 159 {
 160     DLog2(@"[CDragSource removeFromView]: %@\n", self);
 161 
 162     // Remove this dragging source from the view:
 163     [((AWTView *) fView) setDragSource:nil];
 164 
 165     // Clean up JNI refs
 166     if (fComponent != NULL) {
 167         JNFDeleteGlobalRef(env, fComponent);
 168         fComponent = NULL;
 169     }
 170 
 171     if (fDragSourceContextPeer != NULL) {
 172         JNFDeleteGlobalRef(env, fDragSourceContextPeer);
 173         fDragSourceContextPeer = NULL;
 174     }
 175 
 176     if (fTransferable != NULL) {
 177         JNFDeleteGlobalRef(env, fTransferable);
 178         fTransferable = NULL;
 179     }
 180 
 181     if (fTriggerEvent != NULL) {
 182         JNFDeleteGlobalRef(env, fTriggerEvent);
 183         fTriggerEvent = NULL;
 184     }
 185 
 186     if (fFormats != NULL) {
 187         JNFDeleteGlobalRef(env, fFormats);
 188         fFormats = NULL;
 189     }
 190 
 191     if (fFormatMap != NULL) {
 192         JNFDeleteGlobalRef(env, fFormatMap);
 193         fFormatMap = NULL;
 194     }
 195 
 196     CFRelease(self); // GC
 197 }
 198 
 199 - (void)dealloc
 200 {
 201     DLog2(@"[CDragSource dealloc]: %@\n", self);
 202 
 203     // Delete or release local data:
 204     [fView release];
 205     fView = nil;
 206 
 207     [fDragImage release];
 208     fDragImage = nil;
 209 
 210     [super dealloc];
 211 }
 212 //- (void)finalize { [super finalize]; }
 213 
 214 
 215 // Appropriated from Windows' awt_DataTransferer.cpp:
 216 //
 217 // * NOTE: This returns a JNI Local Ref. Any code that calls must call DeleteLocalRef with the return value.
 218 //
 219 - (jobject)dataTransferer:(JNIEnv*)env
 220 {
 221     JNF_STATIC_MEMBER_CACHE(getInstanceMethod, DataTransfererClass, "getInstance", "()Lsun/awt/datatransfer/DataTransferer;");
 222     return JNFCallStaticObjectMethod(env, getInstanceMethod);
 223 }
 224 
 225 // Appropriated from Windows' awt_DataTransferer.cpp:
 226 //
 227 // * NOTE: This returns a JNI Local Ref. Any code that calls must call DeleteLocalRef with the return value.
 228 //
 229 - (jbyteArray)convertData:(jlong)format
 230 {
 231     JNIEnv*    env = [ThreadUtilities getJNIEnv];
 232     jobject    transferer = [self dataTransferer:env];
 233     jbyteArray data = nil;
 234 
 235     if (transferer != NULL) {
 236         JNF_MEMBER_CACHE(convertDataMethod, DataTransfererClass, "convertData", "(Ljava/lang/Object;Ljava/awt/datatransfer/Transferable;JLjava/util/Map;Z)[B");
 237         data = JNFCallObjectMethod(env, transferer, convertDataMethod, fComponent, fTransferable, format, fFormatMap, (jboolean) TRUE);
 238     }
 239 
 240     return data;
 241 }
 242 
 243 
 244 // Encodes a byte array of zero-terminated filenames into an NSArray of NSStrings representing them.
 245 // Borrowed and adapted from awt_DataTransferer.c, convertFileType().
 246 - (id)getFileList:(jbyte *)jbytes dataLength:(jsize)jbytesLength
 247 {
 248     jsize  strings = 0;
 249     jsize  i;
 250 
 251     // Get number of filenames while making sure to skip over empty strings.
 252     for (i = 1; i < jbytesLength; i++) {
 253         if (jbytes[i] == '\0' && jbytes[i - 1] != '\0')
 254             strings++;
 255     }
 256 
 257     // Create the file list to return:
 258     NSMutableArray* fileList = [NSMutableArray arrayWithCapacity:strings];
 259 
 260     for (i = 0; i < jbytesLength; i++) {
 261         char* start = (char *) &jbytes[i];
 262 
 263         // Skip over empty strings:
 264         if (start[0] == '\0') {
 265             continue;
 266         }
 267 
 268         // Update the position marker:
 269         i += strlen(start);
 270 
 271         // Add this filename to the file list:
 272         NSMutableString* fileName = [NSMutableString stringWithUTF8String:start];
 273         // Decompose the filename
 274         CFStringNormalize((CFMutableStringRef)fileName, kCFStringNormalizationFormD);
 275         [fileList addObject:fileName];
 276     }
 277 
 278     // 03-01-09 Note: keep this around for debugging.
 279     // return [NSArray arrayWithObjects:@"/tmp/foo1", @"/tmp/foo2", nil];
 280 
 281     return ([fileList count] > 0 ? fileList : nil);
 282 }
 283 
 284 
 285 // Set up the pasteboard for dragging:
 286 - (BOOL)declareTypesToPasteboard:(NSPasteboard *)pb withEnv:(JNIEnv *) env {
 287     // 9-20-02 Note: leave this here for debugging:
 288     //[pb declareTypes: [NSArray arrayWithObject: NSStringPboardType] owner: self];
 289     //return TRUE;
 290 
 291     // Get byte array elements:
 292     jboolean isCopy;
 293     jlong* jformats = (*env)->GetLongArrayElements(env, fFormats, &isCopy);
 294     if (jformats == nil)
 295         return FALSE;
 296 
 297     // Allocate storage arrays for dragging types to register with the pasteboard:
 298     jsize formatsLength = (*env)->GetArrayLength(env, fFormats);
 299     NSMutableArray* pbTypes = [[NSMutableArray alloc] initWithCapacity:formatsLength];
 300 
 301     // And assume there are no NS-type data: [Radar 3065621]
 302     // This is to be able to drop transferables containing only a serialized object flavor, e.g.:
 303     //   "JAVA_DATAFLAVOR:application/x-java-serialized-object; class=java.awt.Label".
 304     BOOL hasNSTypeData = false;
 305 
 306     // Collect all supported types in a pasteboard format into the storage arrays:
 307     jsize i;
 308     for (i = 0; i < formatsLength; i++) {
 309         jlong jformat = jformats[i];
 310 
 311         if (jformat >= 0) {
 312             NSString* type = formatForIndex(jformat);
 313 
 314             // Add element type to the storage array.
 315             if (type != nil) {
 316                 if ([type hasPrefix:@"JAVA_DATAFLAVOR:application/x-java-jvm-local-objectref;"] == false) {
 317                     [pbTypes addObject:type];
 318 
 319                     // This is a good approximation if not perfect. A conclusive search would
 320                     // have to be done matching all defined strings in AppKit's commonStrings.h.
 321                     if ([type hasPrefix:@"NS"] || [type hasPrefix:@"NeXT"])
 322                         hasNSTypeData = true;
 323                 }
 324             }
 325         }
 326     }
 327 
 328     // 1-16-03 Note: [Radar 3065621]
 329     // When TransferHandler is used with Swing components it puts only a type like this on the pasteboard:
 330     //   "JAVA_DATAFLAVOR:application/x-java-jvm-local-objectref; class=java.lang.String"
 331     // And there's similar type for serialized object only transferables.
 332     // Since our drop targets aren't trained for arbitrary data types yet we need to fake an empty string
 333     // which will cause drop target handlers to fire.
 334     // KCH  - 3550405 If the drag is between Swing components, formatsLength == 0, so expand the check.
 335     // Also, use a custom format rather than NSString, since that will prevent random views from accepting the drag
 336     if (hasNSTypeData == false && formatsLength >= 0) {
 337         [pbTypes addObject:[DnDUtilities javaPboardType]];
 338     }
 339 
 340     (*env)->ReleaseLongArrayElements(env, fFormats, jformats, JNI_ABORT);
 341 
 342     // Declare pasteboard types. If the types array is empty we still want to declare them
 343     // as otherwise an old set of types/data would remain on the pasteboard.
 344     NSUInteger typesCount = [pbTypes count];
 345     [pb declareTypes:pbTypes owner: self];
 346 
 347     // KCH - Lame conversion bug between Cocoa and Carbon drag types
 348     // If I provide the filenames _right now_, NSFilenamesPboardType is properly converted to CoreDrag flavors
 349     // If I try to wait until pasteboard:provideDataForType:, the conversion won't happen
 350     // and pasteboard:provideDataForType: won't even get called! (unless I go over a Cocoa app)
 351     if ([pbTypes containsObject:NSFilenamesPboardType]) {
 352         [self pasteboard:pb provideDataForType:NSFilenamesPboardType];
 353     }
 354 
 355     [pbTypes release];
 356 
 357     return typesCount > 0 ? TRUE : FALSE;
 358 }
 359 
 360 // This is an NSPasteboard callback. In declareTypesToPasteboard:withEnv:, we only declared the types
 361 // When the AppKit DnD system actually needs the data, this method will be invoked.
 362 // Note that if the transfer is handled entirely from Swing (as in a local-vm drag), this method may never be called.
 363 - (void)pasteboard:(NSPasteboard *)pb provideDataForType:(NSString *)type {
 364     AWT_ASSERT_APPKIT_THREAD;
 365 
 366     // 9-20-02 Note: leave this here for debugging:
 367     //[pb setString: @"Hello, World!" forType: NSStringPboardType];
 368     // return;
 369 
 370     // Set up Java environment:
 371     JNIEnv* env = [ThreadUtilities getJNIEnv];
 372 
 373     id pbData = nil;
 374 
 375     // Collect data in a pasteboard format:
 376     jlong jformat = indexForFormat(type);
 377     if (jformat >= 0) {
 378         // Convert DataTransfer data to a Java byte array:
 379         // Note that this will eventually call getTransferData()
 380         jbyteArray jdata = [self convertData:jformat];
 381 
 382         if (jdata != nil) {
 383             jboolean isCopy;
 384             jsize jdataLength = (*env)->GetArrayLength(env, jdata);
 385             jbyte* jbytedata = (*env)->GetByteArrayElements(env, jdata, &isCopy);
 386 
 387             if (jdataLength > 0 && jbytedata != nil) {
 388                 // Get element data to the storage array. For NSFilenamesPboardType type we use
 389                 // an NSArray-type data - NSData-type data would cause a crash.
 390                 if (type != nil) {
 391                     pbData = ([type isEqualTo:NSFilenamesPboardType]) ?
 392                         [self getFileList:jbytedata dataLength:jdataLength] :
 393                         [NSData dataWithBytes:jbytedata length:jdataLength];
 394                 }
 395             }
 396 
 397             (*env)->ReleaseByteArrayElements(env, jdata, jbytedata, JNI_ABORT);
 398 
 399             (*env)->DeleteLocalRef(env, jdata);
 400         }
 401     }
 402 
 403     // If we are the custom type that matches local-vm drags, set an empty NSData
 404     if ( (pbData == nil) && ([type isEqualTo:[DnDUtilities javaPboardType]]) ) {
 405         pbData = [NSData dataWithBytes:"" length:1];
 406     }
 407 
 408     // Add pasteboard data for the type:
 409     // Remember, NSFilenamesPboardType's data is NSArray (property list), not NSData!
 410     // We must use proper pb accessor depending on the data type.
 411     if ([pbData isKindOfClass:[NSArray class]])
 412         [pb setPropertyList:pbData forType:type];
 413     else
 414         [pb setData:pbData forType:type];
 415 }
 416 
 417 
 418 - (void)validateDragImage
 419 {
 420     // Make a small blank image if we don't have a drag image:
 421     if (fDragImage == nil) {
 422         // 9-30-02 Note: keep this around for debugging:
 423         fDragImage = [[NSImage alloc] initWithSize:NSMakeSize(21, 21)];
 424         NSSize imageSize = [fDragImage size];
 425 
 426         NSBitmapImageRep *imageRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL
 427             pixelsWide:imageSize.width pixelsHigh:imageSize.height bitsPerSample:8 samplesPerPixel:4
 428             hasAlpha:YES isPlanar:NO colorSpaceName:NSCalibratedRGBColorSpace bytesPerRow:0 bitsPerPixel:32];
 429 
 430         [fDragImage addRepresentation:imageRep];
 431         fDragImageOffset = NSMakePoint(0, 0);
 432 
 433         [imageRep release];
 434     }
 435 }
 436 
 437 - (NSEvent*)nsDragEvent:(BOOL)isDrag
 438 {
 439     // Get NSView for the drag source:
 440     NSWindow* window = [fView window];
 441 
 442     NSInteger windowNumber = [window windowNumber];
 443     NSGraphicsContext* graphicsContext = [NSGraphicsContext graphicsContextWithWindow:window];
 444 
 445     // Convert mouse coordinates to NS:
 446     NSPoint eventLocation = [fView convertPoint:NSMakePoint(fDragPos.x, fDragPos.y) toView:nil];
 447     eventLocation.y = [[fView window] frame].size.height - eventLocation.y;
 448     
 449     // Convert fTriggerEventTimeStamp to NS - AWTEvent.h defines UTC(nsEvent) as ((jlong)[event timestamp] * 1000):
 450     NSTimeInterval timeStamp = fTriggerEventTimeStamp / 1000;
 451 
 452     // Convert fModifiers (extModifiers) to NS:
 453     NSEventType mouseButtons = 0;
 454     float pressure = 0.0;
 455     if (isDrag) {
 456         mouseButtons = (NSEventType) [DnDUtilities mapJavaExtModifiersToNSMouseDownButtons:fModifiers];
 457         pressure = 1.0;
 458     } else {
 459         mouseButtons = (NSEventType) [DnDUtilities mapJavaExtModifiersToNSMouseUpButtons:fModifiers];
 460     }
 461 
 462     // Convert fModifiers (extModifiers) to NS:
 463     NSUInteger modifiers = JavaModifiersToNsKeyModifiers(fModifiers, TRUE); 
 464 
 465     // Just a dummy value ...
 466     NSInteger eventNumber = 0;
 467 
 468     // Make a native autoreleased dragging event:
 469     NSEvent* dragEvent = [NSEvent mouseEventWithType:mouseButtons location:eventLocation
 470         modifierFlags:modifiers timestamp:timeStamp windowNumber:windowNumber context:graphicsContext
 471         eventNumber:eventNumber clickCount:fClickCount pressure:pressure];
 472 
 473     return dragEvent;
 474 }
 475 
 476 - (void)doDrag
 477 {
 478     AWT_ASSERT_APPKIT_THREAD;
 479 
 480     DLog2(@"[CDragSource doDrag]: %@\n", self);
 481 
 482     // Set up Java environment:
 483     JNIEnv *env = [ThreadUtilities getJNIEnv];
 484 
 485     // Set up the pasteboard:
 486     NSPasteboard *pb = [NSPasteboard pasteboardWithName: NSDragPboard];
 487     [self declareTypesToPasteboard:pb withEnv:env];
 488 
 489     // Make a native autoreleased NS dragging event:
 490     NSEvent *dragEvent = [self nsDragEvent:YES];
 491 
 492     // Get NSView for the drag source:
 493     NSView *view = fView;
 494 
 495     // Make sure we have a valid drag image:
 496     [self validateDragImage];
 497     NSImage* dragImage = fDragImage;
 498 
 499     // Get drag origin and offset:
 500     NSPoint dragOrigin = [dragEvent locationInWindow];
 501     dragOrigin.x += fDragImageOffset.x;
 502     dragOrigin.y -= fDragImageOffset.y + [dragImage size].height;
 503 
 504     // Drag offset values don't seem to matter:
 505     NSSize dragOffset = NSMakeSize(0, 0);
 506 
 507     // These variables should be set based on the transferable:
 508     BOOL isFileDrag = FALSE;
 509     BOOL fileDragPromises = FALSE;
 510 
 511     DLog(@"[CDragSource drag]: calling dragImage/File:");
 512     DLog3(@"  - drag origin: %f, %f", fDragPos.x, fDragPos.y);
 513     DLog5(@"  - drag image: %f, %f (%f x %f)", fDragImageOffset.x, fDragImageOffset.y, [dragImage size].width, [dragImage size].height);
 514     DLog3(@"  - event point (window) %f, %f", [dragEvent locationInWindow].x, [dragEvent locationInWindow].y);
 515     DLog3(@"  - drag point (view) %f, %f", dragOrigin.x, dragOrigin.y);
 516     // Set up the fDragKeyModifier, so we know if the operation has changed
 517     // Set up the fDragMouseModifier, so we can |= it later (since CoreDrag doesn't tell us mouse states during a drag)
 518     fDragKeyModifiers = [DnDUtilities extractJavaExtKeyModifiersFromJavaExtModifiers:fModifiers];
 519     fDragMouseModifiers = [DnDUtilities extractJavaExtMouseModifiersFromJavaExtModifiers:fModifiers];
 520 
 521     sNeedsEnter = YES;
 522 
 523     @try {
 524         // Data dragging:
 525         if (isFileDrag == FALSE) {
 526             [view dragImage:dragImage at:dragOrigin offset:dragOffset event:dragEvent pasteboard:pb source:view slideBack:YES];
 527         } else if (fileDragPromises == FALSE) {
 528             // File dragging:
 529             NSLog(@"[CDragSource drag]: file dragging is unsupported.");
 530             NSString* fileName = nil;                                // This should be set based on the transferable.
 531             NSRect    fileLocationRect = NSMakeRect(0, 0, 0, 0);    // This should be set based on the filename.
 532 
 533             BOOL success = [view dragFile:fileName fromRect:fileLocationRect slideBack:YES event:dragEvent];
 534             if (success == TRUE) {                                    // One would erase dragged file if this was a move operation.
 535             }
 536         } else {
 537             // Promised file dragging:
 538             NSLog(@"[CDragSource drag]: file dragging promises are unsupported.");
 539             NSArray* fileTypesArray = nil;                            // This should be set based on the transferable.
 540             NSRect   fileLocationRect = NSMakeRect(0, 0, 0, 0);        // This should be set based on all filenames.
 541 
 542             BOOL success = [view dragPromisedFilesOfTypes:fileTypesArray fromRect:fileLocationRect source:view slideBack:YES event:dragEvent];
 543             if (success == TRUE) {                                    // One would write out the promised files here.
 544             }
 545         }
 546 
 547         NSPoint point = [self mapNSScreenPointToJavaWithOffset:sDraggingLocation];
 548 
 549         // Convert drag operation to Java:
 550         jint dragOp = [DnDUtilities mapNSDragOperationToJava:sDragOperation];
 551 
 552         // Drag success must acount for DragOperationNone:
 553         jboolean success = (dragOp != java_awt_dnd_DnDConstants_ACTION_NONE);
 554 
 555         // We have a problem here... we don't send DragSource dragEnter/Exit messages outside of our own process
 556         // because we don't get anything from AppKit/CoreDrag
 557         // This means that if you drag outside of the app and drop, even if it's valid, a dragDropFinished is posted without dragEnter
 558         // I'm worried that this might confuse Java, so we're going to send a "bogus" dragEnter if necessary (only if the drag succeeded)
 559         if (success && sNeedsEnter) {
 560             [self postDragEnter];
 561         }
 562 
 563         // DragSourceContextPeer.dragDropFinished() should be called even if there was an error:
 564         JNF_MEMBER_CACHE(dragDropFinishedMethod, CDragSourceContextPeerClass, "dragDropFinished", "(ZIII)V");
 565         DLog3(@"  -> posting dragDropFinished, point %f, %f", point.x, point.y);
 566         JNFCallVoidMethod(env, fDragSourceContextPeer, dragDropFinishedMethod, success, dragOp, (jint) point.x, (jint) point.y); // AWT_THREADING Safe (event)
 567                 JNF_MEMBER_CACHE(resetHoveringMethod, CDragSourceContextPeerClass, "resetHovering", "()V");
 568         JNFCallVoidMethod(env, fDragSourceContextPeer, resetHoveringMethod); // Hust reset static variable
 569     } @finally {
 570         sNeedsEnter = NO;
 571     }
 572 
 573     // We have to do this, otherwise AppKit doesn't know we're finished dragging. Yup, it's that bad.
 574     if ([[[NSRunLoop currentRunLoop] currentMode] isEqualTo:NSEventTrackingRunLoopMode]) {
 575         [NSApp postEvent:[self nsDragEvent:NO] atStart:YES];
 576     }
 577 
 578     DLog2(@"[CDragSource doDrag] end: %@\n", self);
 579 }
 580 
 581 - (void)drag
 582 {
 583     AWT_ASSERT_NOT_APPKIT_THREAD;
 584 
 585     [self performSelectorOnMainThread:@selector(doDrag) withObject:nil waitUntilDone:YES]; // AWT_THREADING Safe (called from unique asynchronous thread)
 586 }
 587 
 588 /********************************  BEGIN NSDraggingSource Interface  ********************************/
 589 
 590 - (void)draggingOperationChanged:(NSDragOperation)dragOp {
 591     //DLog2(@"[CDragSource draggingOperationChanged]: %@\n", self);
 592 
 593     JNIEnv* env = [ThreadUtilities getJNIEnv];
 594 
 595     jint targetActions = fSourceActions;
 596     if ([CDropTarget currentDropTarget]) targetActions = [[CDropTarget currentDropTarget] currentJavaActions];
 597 
 598     NSPoint point = [self mapNSScreenPointToJavaWithOffset:sDraggingLocation];
 599     DLog3(@"  -> posting operationChanged, point %f, %f", point.x, point.y);
 600     jint modifiedModifiers = fDragKeyModifiers | fDragMouseModifiers | [DnDUtilities javaKeyModifiersForNSDragOperation:dragOp];
 601 
 602     JNF_MEMBER_CACHE(operationChangedMethod, CDragSourceContextPeerClass, "operationChanged", "(IIII)V");
 603     JNFCallVoidMethod(env, fDragSourceContextPeer, operationChangedMethod, targetActions, modifiedModifiers, (jint) point.x, (jint) point.y); // AWT_THREADING Safe (event)
 604 }
 605 
 606 - (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)localDrag {
 607     //DLog2(@"[CDragSource draggingSourceOperationMaskForLocal]: %@\n", self);
 608     return [DnDUtilities mapJavaDragOperationToNS:fSourceActions];
 609 }
 610 
 611 /* 9-16-02 Note: we don't support promises yet.
 612 - (NSArray *)namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination {
 613 }*/
 614 
 615 - (void)draggedImage:(NSImage *)image beganAt:(NSPoint)screenPoint {
 616     DLog4(@"[CDragSource draggedImage beganAt]: (%f, %f) %@\n", screenPoint.x, screenPoint.y, self);
 617 
 618     // Initialize static variables:
 619     sDragOperation = NSDragOperationNone;
 620     sDraggingLocation = screenPoint;
 621 }
 622 
 623 - (void)draggedImage:(NSImage *)image endedAt:(NSPoint)screenPoint operation:(NSDragOperation)operation {
 624     DLog4(@"[CDragSource draggedImage endedAt:]: (%f, %f) %@\n", screenPoint.x, screenPoint.y, self);
 625 
 626     sDraggingLocation = screenPoint;
 627     sDragOperation = operation;
 628 }
 629 
 630 - (void)draggedImage:(NSImage *)image movedTo:(NSPoint)screenPoint {
 631     //DLog4(@"[CDragSource draggedImage moved]: (%d, %d) %@\n", (int) screenPoint.x, (int) screenPoint.y, self);
 632     JNIEnv* env = [ThreadUtilities getJNIEnv];
 633 
 634 JNF_COCOA_ENTER(env);
 635     // There are two things we would be interested in:
 636     // a) mouse pointer has moved
 637     // b) drag actions (key modifiers) have changed
 638 
 639     BOOL notifyJava = FALSE;
 640 
 641     // a) mouse pointer has moved:
 642     if (NSEqualPoints(screenPoint, sDraggingLocation) == FALSE) {
 643         //DLog2(@"[CDragSource draggedImage:movedTo]: mouse moved, %@\n", self);
 644         notifyJava = TRUE;
 645     }
 646 
 647     // b) drag actions (key modifiers) have changed:
 648     jint modifiers = NsKeyModifiersToJavaModifiers([NSEvent modifierFlags], YES);
 649     if (fDragKeyModifiers != modifiers) {
 650         NSDragOperation currentOp = [DnDUtilities nsDragOperationForModifiers:[NSEvent modifierFlags]];
 651         NSDragOperation allowedOp = [DnDUtilities mapJavaDragOperationToNS:fSourceActions] & currentOp;
 652 
 653         fDragKeyModifiers = modifiers;
 654 
 655         if (sDragOperation != allowedOp) {
 656             sDragOperation = allowedOp;
 657             [self draggingOperationChanged:allowedOp];
 658         }
 659     }
 660 
 661     // Should we notify Java things have changed?
 662     if (notifyJava) {
 663         sDraggingLocation = screenPoint;
 664 
 665         NSPoint point = [self mapNSScreenPointToJavaWithOffset:screenPoint];
 666 
 667         jint targetActions = fSourceActions;
 668         if ([CDropTarget currentDropTarget]) targetActions = [[CDropTarget currentDropTarget] currentJavaActions];
 669 
 670         // Motion: dragMotion, dragMouseMoved
 671         DLog4(@"[CDragSource draggedImage moved]: (%f, %f) %@\n", screenPoint.x, screenPoint.y, self);
 672 
 673         DLog3(@"  -> posting dragMotion, point %f, %f", point.x, point.y);
 674         JNF_MEMBER_CACHE(dragMotionMethod, CDragSourceContextPeerClass, "dragMotion", "(IIII)V");
 675         JNFCallVoidMethod(env, fDragSourceContextPeer, dragMotionMethod, targetActions, (jint) fModifiers, (jint) point.x, (jint) point.y); // AWT_THREADING Safe (event)
 676 
 677         DLog3(@"  -> posting dragMouseMoved, point %f, %f", point.x, point.y);
 678         JNF_MEMBER_CACHE(dragMouseMovedMethod, CDragSourceContextPeerClass, "dragMouseMoved", "(IIII)V");
 679         JNFCallVoidMethod(env, fDragSourceContextPeer, dragMouseMovedMethod, targetActions, (jint) fModifiers, (jint) point.x, (jint) point.y); // AWT_THREADING Safe (event)
 680     }
 681 JNF_COCOA_EXIT(env);
 682 }
 683 
 684 - (BOOL)ignoreModifierKeysWhileDragging {
 685     //DLog2(@"[CDragSource ignoreModifierKeysWhileDragging]: %@\n", self);
 686     return NO;
 687 }
 688 
 689 /********************************  END NSDraggingSource Interface  ********************************/
 690 
 691 
 692 // postDragEnter and postDragExit are called from CDropTarget when possible and appropriate
 693 // Currently only possible if source and target are in the same process
 694 - (void) postDragEnter {
 695     JNIEnv *env = [ThreadUtilities getJNIEnv];
 696     sNeedsEnter = NO;
 697 
 698     jint targetActions = fSourceActions;
 699     if ([CDropTarget currentDropTarget]) targetActions = [[CDropTarget currentDropTarget] currentJavaActions];
 700 
 701     NSPoint point = [self mapNSScreenPointToJavaWithOffset:sDraggingLocation];
 702     DLog3(@"  -> posting dragEnter, point %f, %f", point.x, point.y);
 703     JNF_MEMBER_CACHE(dragEnterMethod, CDragSourceContextPeerClass, "dragEnter", "(IIII)V");
 704     JNFCallVoidMethod(env, fDragSourceContextPeer, dragEnterMethod, targetActions, (jint) fModifiers, (jint) point.x, (jint) point.y); // AWT_THREADING Safe (event)
 705 }
 706 
 707 - (void) postDragExit {
 708     JNIEnv *env = [ThreadUtilities getJNIEnv];
 709     sNeedsEnter = YES;
 710 
 711     NSPoint point = [self mapNSScreenPointToJavaWithOffset:sDraggingLocation];
 712     DLog3(@"  -> posting dragExit, point %f, %f", point.x, point.y);
 713     JNF_MEMBER_CACHE(dragExitMethod, CDragSourceContextPeerClass, "dragExit", "(II)V");
 714     JNFCallVoidMethod(env, fDragSourceContextPeer, dragExitMethod, (jint) point.x, (jint) point.y); // AWT_THREADING Safe (event)
 715 }
 716 
 717 
 718 // Java assumes that the origin is the top-left corner of the screen.
 719 // Cocoa assumes that the origin is the bottom-left corner of the screen.
 720 // Adjust the y coordinate to account for this.
 721 // NOTE: Also need to take into account the 0 screen relative screen coords.
 722 //  This is because all screen coords in Cocoa are relative to the 0 screen.
 723 // Also see +[CWindow convertAWTToCocoaScreenRect]
 724 // NSScreen-to-JavaScreen mapping:
 725 - (NSPoint) mapNSScreenPointToJavaWithOffset:(NSPoint)screenPoint {
 726     NSRect mainR = [[[NSScreen screens] objectAtIndex:0] frame];
 727     NSPoint point = NSMakePoint(screenPoint.x, mainR.size.height - (screenPoint.y));
 728 
 729     // Adjust the point with the drag image offset to get the real mouse hotspot:
 730     // The point should remain in screen coordinates (as per DragSourceEvent.getLocation() documentation)
 731     point.x -= fDragImageOffset.x;
 732     point.y -= ([fDragImage size].height + fDragImageOffset.y);
 733 
 734     return point;
 735 }
 736 
 737 @end