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