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);
 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                     hasNSTypeData = [type hasPrefix:@"NS"] || [type hasPrefix:@"NeXT"] || [type hasPrefix:@"public."];
 317                 }
 318             }
 319         }
 320     }
 321 
 322     // 1-16-03 Note: [Radar 3065621]
 323     // When TransferHandler is used with Swing components it puts only a type like this on the pasteboard:
 324     //   "JAVA_DATAFLAVOR:application/x-java-jvm-local-objectref; class=java.lang.String"
 325     // And there's similar type for serialized object only transferables.
 326     // Since our drop targets aren't trained for arbitrary data types yet we need to fake an empty string
 327     // which will cause drop target handlers to fire.
 328     // KCH  - 3550405 If the drag is between Swing components, formatsLength == 0, so expand the check.
 329     // Also, use a custom format rather than NSString, since that will prevent random views from accepting the drag
 330     if (hasNSTypeData == false && formatsLength >= 0) {
 331         [pbTypes addObject:[DnDUtilities javaPboardType]];
 332     }
 333 
 334     (*env)->ReleaseLongArrayElements(env, fFormats, jformats, JNI_ABORT);
 335 
 336     // Declare pasteboard types. If the types array is empty we still want to declare them
 337     // as otherwise an old set of types/data would remain on the pasteboard.
 338     NSUInteger typesCount = [pbTypes count];
 339     [pb declareTypes:pbTypes owner: self];
 340 
 341     // KCH - Lame conversion bug between Cocoa and Carbon drag types
 342     // If I provide the filenames _right now_, NSFilenamesPboardType is properly converted to CoreDrag flavors
 343     // If I try to wait until pasteboard:provideDataForType:, the conversion won't happen
 344     // and pasteboard:provideDataForType: won't even get called! (unless I go over a Cocoa app)
 345     if ([pbTypes containsObject:NSFilenamesPboardType]) {
 346         [self pasteboard:pb provideDataForType:NSFilenamesPboardType];
 347     }
 348 
 349     [pbTypes release];
 350 
 351     return typesCount > 0 ? TRUE : FALSE;
 352 }
 353 
 354 // This is an NSPasteboard callback. In declareTypesToPasteboard:withEnv:, we only declared the types
 355 // When the AppKit DnD system actually needs the data, this method will be invoked.
 356 // Note that if the transfer is handled entirely from Swing (as in a local-vm drag), this method may never be called.
 357 - (void)pasteboard:(NSPasteboard *)pb provideDataForType:(NSString *)type {
 358     AWT_ASSERT_APPKIT_THREAD;
 359 
 360     // 9-20-02 Note: leave this here for debugging:
 361     //[pb setString: @"Hello, World!" forType: NSStringPboardType];
 362     // return;
 363 
 364     // Set up Java environment:
 365     JNIEnv* env = [ThreadUtilities getJNIEnv];
 366 
 367     id pbData = nil;
 368 
 369     // Collect data in a pasteboard format:
 370     jlong jformat = indexForFormat(type);
 371     if (jformat >= 0) {
 372         // Convert DataTransfer data to a Java byte array:
 373         // Note that this will eventually call getTransferData()
 374         jbyteArray jdata = [self convertData:jformat];
 375 
 376         if (jdata != nil) {
 377             jboolean isCopy;
 378             jsize jdataLength = (*env)->GetArrayLength(env, jdata);
 379             jbyte* jbytedata = (*env)->GetByteArrayElements(env, jdata, &isCopy);
 380 
 381             if (jdataLength > 0 && jbytedata != nil) {
 382                 // Get element data to the storage array. For NSFilenamesPboardType type we use
 383                 // an NSArray-type data - NSData-type data would cause a crash.
 384                 if (type != nil) {
 385                     pbData = ([type isEqualTo:NSFilenamesPboardType]) ?
 386                         [self getFileList:jbytedata dataLength:jdataLength] :
 387                         [NSData dataWithBytes:jbytedata length:jdataLength];
 388                 }
 389             }
 390 
 391             (*env)->ReleaseByteArrayElements(env, jdata, jbytedata, JNI_ABORT);
 392 
 393             (*env)->DeleteLocalRef(env, jdata);
 394         }
 395     }
 396 
 397     // If we are the custom type that matches local-vm drags, set an empty NSData
 398     if ( (pbData == nil) && ([type isEqualTo:[DnDUtilities javaPboardType]]) ) {
 399         pbData = [NSData dataWithBytes:"" length:1];
 400     }
 401 
 402     // Add pasteboard data for the type:
 403     // Remember, NSFilenamesPboardType's data is NSArray (property list), not NSData!
 404     // We must use proper pb accessor depending on the data type.
 405     if ([pbData isKindOfClass:[NSArray class]])
 406         [pb setPropertyList:pbData forType:type];
 407     else
 408         [pb setData:pbData forType:type];
 409 }
 410 
 411 
 412 - (void)validateDragImage
 413 {
 414     // Make a small blank image if we don't have a drag image:
 415     if (fDragImage == nil) {
 416         // 9-30-02 Note: keep this around for debugging:
 417         fDragImage = [[NSImage alloc] initWithSize:NSMakeSize(21, 21)];
 418         NSSize imageSize = [fDragImage size];
 419 
 420         NSBitmapImageRep *imageRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL
 421             pixelsWide:imageSize.width pixelsHigh:imageSize.height bitsPerSample:8 samplesPerPixel:4
 422             hasAlpha:YES isPlanar:NO colorSpaceName:NSCalibratedRGBColorSpace bytesPerRow:0 bitsPerPixel:32];
 423 
 424         [fDragImage addRepresentation:imageRep];
 425         fDragImageOffset = NSMakePoint(0, 0);
 426 
 427         [imageRep release];
 428     }
 429 }
 430 
 431 - (NSEvent*)nsDragEvent:(BOOL)isDrag
 432 {
 433     // Get NSView for the drag source:
 434     NSWindow* window = [fView window];
 435 
 436     NSInteger windowNumber = [window windowNumber];
 437     NSGraphicsContext* graphicsContext = [NSGraphicsContext graphicsContextWithWindow:window];
 438 
 439     // Convert mouse coordinates to NS:
 440     NSPoint eventLocation = [fView convertPoint:NSMakePoint(fDragPos.x, fDragPos.y) toView:nil];
 441     eventLocation.y = [[fView window] frame].size.height - eventLocation.y;
 442     
 443     // Convert fTriggerEventTimeStamp to NS - AWTEvent.h defines UTC(nsEvent) as ((jlong)[event timestamp] * 1000):
 444     NSTimeInterval timeStamp = fTriggerEventTimeStamp / 1000;
 445 
 446     // Convert fModifiers (extModifiers) to NS:
 447     NSEventType mouseButtons = 0;
 448     float pressure = 0.0;
 449     if (isDrag) {
 450         mouseButtons = (NSEventType) [DnDUtilities mapJavaExtModifiersToNSMouseDownButtons:fModifiers];
 451         pressure = 1.0;
 452     } else {
 453         mouseButtons = (NSEventType) [DnDUtilities mapJavaExtModifiersToNSMouseUpButtons:fModifiers];
 454     }
 455 
 456     // Convert fModifiers (extModifiers) to NS:
 457     NSUInteger modifiers = JavaModifiersToNsKeyModifiers(fModifiers, TRUE); 
 458 
 459     // Just a dummy value ...
 460     NSInteger eventNumber = 0;
 461 
 462     // Make a native autoreleased dragging event:
 463     NSEvent* dragEvent = [NSEvent mouseEventWithType:mouseButtons location:eventLocation
 464         modifierFlags:modifiers timestamp:timeStamp windowNumber:windowNumber context:graphicsContext
 465         eventNumber:eventNumber clickCount:fClickCount pressure:pressure];
 466 
 467     return dragEvent;
 468 }
 469 
 470 - (void)doDrag
 471 {
 472     AWT_ASSERT_APPKIT_THREAD;
 473 
 474     DLog2(@"[CDragSource doDrag]: %@\n", self);
 475 
 476     // Set up Java environment:
 477     JNIEnv *env = [ThreadUtilities getJNIEnv];
 478 
 479     // Set up the pasteboard:
 480     NSPasteboard *pb = [NSPasteboard pasteboardWithName: NSDragPboard];
 481     [self declareTypesToPasteboard:pb withEnv:env];
 482 
 483     // Make a native autoreleased NS dragging event:
 484     NSEvent *dragEvent = [self nsDragEvent:YES];
 485 
 486     // Get NSView for the drag source:
 487     NSView *view = fView;
 488 
 489     // Make sure we have a valid drag image:
 490     [self validateDragImage];
 491     NSImage* dragImage = fDragImage;
 492 
 493     // Get drag origin and offset:
 494     NSPoint dragOrigin = [dragEvent locationInWindow];
 495     dragOrigin.x += fDragImageOffset.x;
 496     dragOrigin.y -= fDragImageOffset.y + [dragImage size].height;
 497 
 498     // Drag offset values don't seem to matter:
 499     NSSize dragOffset = NSMakeSize(0, 0);
 500 
 501     // These variables should be set based on the transferable:
 502     BOOL isFileDrag = FALSE;
 503     BOOL fileDragPromises = FALSE;
 504 
 505     DLog(@"[CDragSource drag]: calling dragImage/File:");
 506     DLog3(@"  - drag origin: %f, %f", fDragPos.x, fDragPos.y);
 507     DLog5(@"  - drag image: %f, %f (%f x %f)", fDragImageOffset.x, fDragImageOffset.y, [dragImage size].width, [dragImage size].height);
 508     DLog3(@"  - event point (window) %f, %f", [dragEvent locationInWindow].x, [dragEvent locationInWindow].y);
 509     DLog3(@"  - drag point (view) %f, %f", dragOrigin.x, dragOrigin.y);
 510     // Set up the fDragKeyModifier, so we know if the operation has changed
 511     // Set up the fDragMouseModifier, so we can |= it later (since CoreDrag doesn't tell us mouse states during a drag)
 512     fDragKeyModifiers = [DnDUtilities extractJavaExtKeyModifiersFromJavaExtModifiers:fModifiers];
 513     fDragMouseModifiers = [DnDUtilities extractJavaExtMouseModifiersFromJavaExtModifiers:fModifiers];
 514 
 515     sNeedsEnter = YES;
 516 
 517     @try {
 518         // Data dragging:
 519         if (isFileDrag == FALSE) {
 520             [view dragImage:dragImage at:dragOrigin offset:dragOffset event:dragEvent pasteboard:pb source:view slideBack:YES];
 521         } else if (fileDragPromises == FALSE) {
 522             // File dragging:
 523             NSLog(@"[CDragSource drag]: file dragging is unsupported.");
 524             NSString* fileName = nil;                                // This should be set based on the transferable.
 525             NSRect    fileLocationRect = NSMakeRect(0, 0, 0, 0);    // This should be set based on the filename.
 526 
 527             BOOL success = [view dragFile:fileName fromRect:fileLocationRect slideBack:YES event:dragEvent];
 528             if (success == TRUE) {                                    // One would erase dragged file if this was a move operation.
 529             }
 530         } else {
 531             // Promised file dragging:
 532             NSLog(@"[CDragSource drag]: file dragging promises are unsupported.");
 533             NSArray* fileTypesArray = nil;                            // This should be set based on the transferable.
 534             NSRect   fileLocationRect = NSMakeRect(0, 0, 0, 0);        // This should be set based on all filenames.
 535 
 536             BOOL success = [view dragPromisedFilesOfTypes:fileTypesArray fromRect:fileLocationRect source:view slideBack:YES event:dragEvent];
 537             if (success == TRUE) {                                    // One would write out the promised files here.
 538             }
 539         }
 540 
 541         NSPoint point = [self mapNSScreenPointToJavaWithOffset:sDraggingLocation];
 542 
 543         // Convert drag operation to Java:
 544         jint dragOp = [DnDUtilities mapNSDragOperationToJava:sDragOperation];
 545 
 546         // Drag success must acount for DragOperationNone:
 547         jboolean success = (dragOp != java_awt_dnd_DnDConstants_ACTION_NONE);
 548 
 549         // We have a problem here... we don't send DragSource dragEnter/Exit messages outside of our own process
 550         // because we don't get anything from AppKit/CoreDrag
 551         // This means that if you drag outside of the app and drop, even if it's valid, a dragDropFinished is posted without dragEnter
 552         // I'm worried that this might confuse Java, so we're going to send a "bogus" dragEnter if necessary (only if the drag succeeded)
 553         if (success && sNeedsEnter) {
 554             [self postDragEnter];
 555         }
 556 
 557         // DragSourceContextPeer.dragDropFinished() should be called even if there was an error:
 558         JNF_MEMBER_CACHE(dragDropFinishedMethod, CDragSourceContextPeerClass, "dragDropFinished", "(ZIII)V");
 559         DLog3(@"  -> posting dragDropFinished, point %f, %f", point.x, point.y);
 560         JNFCallVoidMethod(env, fDragSourceContextPeer, dragDropFinishedMethod, success, dragOp, (jint) point.x, (jint) point.y); // AWT_THREADING Safe (event)
 561                 JNF_MEMBER_CACHE(resetHoveringMethod, CDragSourceContextPeerClass, "resetHovering", "()V");
 562         JNFCallVoidMethod(env, fDragSourceContextPeer, resetHoveringMethod); // Hust reset static variable
 563     } @finally {
 564         sNeedsEnter = NO;
 565     }
 566 
 567     // We have to do this, otherwise AppKit doesn't know we're finished dragging. Yup, it's that bad.
 568     if ([[[NSRunLoop currentRunLoop] currentMode] isEqualTo:NSEventTrackingRunLoopMode]) {
 569         [NSApp postEvent:[self nsDragEvent:NO] atStart:YES];
 570     }
 571 
 572     DLog2(@"[CDragSource doDrag] end: %@\n", self);
 573 }
 574 
 575 - (void)drag
 576 {
 577     AWT_ASSERT_NOT_APPKIT_THREAD;
 578 
 579     [self performSelectorOnMainThread:@selector(doDrag) withObject:nil waitUntilDone:YES]; // AWT_THREADING Safe (called from unique asynchronous thread)
 580 }
 581 
 582 /********************************  BEGIN NSDraggingSource Interface  ********************************/
 583 
 584 - (void)draggingOperationChanged:(NSDragOperation)dragOp {
 585     //DLog2(@"[CDragSource draggingOperationChanged]: %@\n", self);
 586 
 587     JNIEnv* env = [ThreadUtilities getJNIEnv];
 588 
 589     jint targetActions = fSourceActions;
 590     if ([CDropTarget currentDropTarget]) targetActions = [[CDropTarget currentDropTarget] currentJavaActions];
 591 
 592     NSPoint point = [self mapNSScreenPointToJavaWithOffset:sDraggingLocation];
 593     DLog3(@"  -> posting operationChanged, point %f, %f", point.x, point.y);
 594     jint modifiedModifiers = fDragKeyModifiers | fDragMouseModifiers | [DnDUtilities javaKeyModifiersForNSDragOperation:dragOp];
 595 
 596     JNF_MEMBER_CACHE(operationChangedMethod, CDragSourceContextPeerClass, "operationChanged", "(IIII)V");
 597     JNFCallVoidMethod(env, fDragSourceContextPeer, operationChangedMethod, targetActions, modifiedModifiers, (jint) point.x, (jint) point.y); // AWT_THREADING Safe (event)
 598 }
 599 
 600 - (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)localDrag {
 601     //DLog2(@"[CDragSource draggingSourceOperationMaskForLocal]: %@\n", self);
 602     return [DnDUtilities mapJavaDragOperationToNS:fSourceActions];
 603 }
 604 
 605 /* 9-16-02 Note: we don't support promises yet.
 606 - (NSArray *)namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination {
 607 }*/
 608 
 609 - (void)draggedImage:(NSImage *)image beganAt:(NSPoint)screenPoint {
 610     DLog4(@"[CDragSource draggedImage beganAt]: (%f, %f) %@\n", screenPoint.x, screenPoint.y, self);
 611 
 612     // Initialize static variables:
 613     sDragOperation = NSDragOperationNone;
 614     sDraggingLocation = screenPoint;
 615 }
 616 
 617 - (void)draggedImage:(NSImage *)image endedAt:(NSPoint)screenPoint operation:(NSDragOperation)operation {
 618     DLog4(@"[CDragSource draggedImage endedAt:]: (%f, %f) %@\n", screenPoint.x, screenPoint.y, self);
 619 
 620     sDraggingLocation = screenPoint;
 621     sDragOperation = operation;
 622 }
 623 
 624 - (void)draggedImage:(NSImage *)image movedTo:(NSPoint)screenPoint {
 625     //DLog4(@"[CDragSource draggedImage moved]: (%d, %d) %@\n", (int) screenPoint.x, (int) screenPoint.y, self);
 626     JNIEnv* env = [ThreadUtilities getJNIEnv];
 627 
 628 JNF_COCOA_ENTER(env);
 629     // There are two things we would be interested in:
 630     // a) mouse pointer has moved
 631     // b) drag actions (key modifiers) have changed
 632 
 633     BOOL notifyJava = FALSE;
 634 
 635     // a) mouse pointer has moved:
 636     if (NSEqualPoints(screenPoint, sDraggingLocation) == FALSE) {
 637         //DLog2(@"[CDragSource draggedImage:movedTo]: mouse moved, %@\n", self);
 638         notifyJava = TRUE;
 639     }
 640 
 641     // b) drag actions (key modifiers) have changed:
 642     jint modifiers = NsKeyModifiersToJavaModifiers([NSEvent modifierFlags], YES);
 643     if (fDragKeyModifiers != modifiers) {
 644         NSDragOperation currentOp = [DnDUtilities nsDragOperationForModifiers:[NSEvent modifierFlags]];
 645         NSDragOperation allowedOp = [DnDUtilities mapJavaDragOperationToNS:fSourceActions] & currentOp;
 646 
 647         fDragKeyModifiers = modifiers;
 648 
 649         if (sDragOperation != allowedOp) {
 650             sDragOperation = allowedOp;
 651             [self draggingOperationChanged:allowedOp];
 652         }
 653     }
 654 
 655     // Should we notify Java things have changed?
 656     if (notifyJava) {
 657         sDraggingLocation = screenPoint;
 658 
 659         NSPoint point = [self mapNSScreenPointToJavaWithOffset:screenPoint];
 660 
 661         jint targetActions = fSourceActions;
 662         if ([CDropTarget currentDropTarget]) targetActions = [[CDropTarget currentDropTarget] currentJavaActions];
 663 
 664         // Motion: dragMotion, dragMouseMoved
 665         DLog4(@"[CDragSource draggedImage moved]: (%f, %f) %@\n", screenPoint.x, screenPoint.y, self);
 666 
 667         DLog3(@"  -> posting dragMotion, point %f, %f", point.x, point.y);
 668         JNF_MEMBER_CACHE(dragMotionMethod, CDragSourceContextPeerClass, "dragMotion", "(IIII)V");
 669         JNFCallVoidMethod(env, fDragSourceContextPeer, dragMotionMethod, targetActions, (jint) fModifiers, (jint) point.x, (jint) point.y); // AWT_THREADING Safe (event)
 670 
 671         DLog3(@"  -> posting dragMouseMoved, point %f, %f", point.x, point.y);
 672         JNF_MEMBER_CACHE(dragMouseMovedMethod, CDragSourceContextPeerClass, "dragMouseMoved", "(IIII)V");
 673         JNFCallVoidMethod(env, fDragSourceContextPeer, dragMouseMovedMethod, targetActions, (jint) fModifiers, (jint) point.x, (jint) point.y); // AWT_THREADING Safe (event)
 674     }
 675 JNF_COCOA_EXIT(env);
 676 }
 677 
 678 - (BOOL)ignoreModifierKeysWhileDragging {
 679     //DLog2(@"[CDragSource ignoreModifierKeysWhileDragging]: %@\n", self);
 680     return NO;
 681 }
 682 
 683 /********************************  END NSDraggingSource Interface  ********************************/
 684 
 685 
 686 // postDragEnter and postDragExit are called from CDropTarget when possible and appropriate
 687 // Currently only possible if source and target are in the same process
 688 - (void) postDragEnter {
 689     JNIEnv *env = [ThreadUtilities getJNIEnv];
 690     sNeedsEnter = NO;
 691 
 692     jint targetActions = fSourceActions;
 693     if ([CDropTarget currentDropTarget]) targetActions = [[CDropTarget currentDropTarget] currentJavaActions];
 694 
 695     NSPoint point = [self mapNSScreenPointToJavaWithOffset:sDraggingLocation];
 696     DLog3(@"  -> posting dragEnter, point %f, %f", point.x, point.y);
 697     JNF_MEMBER_CACHE(dragEnterMethod, CDragSourceContextPeerClass, "dragEnter", "(IIII)V");
 698     JNFCallVoidMethod(env, fDragSourceContextPeer, dragEnterMethod, targetActions, (jint) fModifiers, (jint) point.x, (jint) point.y); // AWT_THREADING Safe (event)
 699 }
 700 
 701 - (void) postDragExit {
 702     JNIEnv *env = [ThreadUtilities getJNIEnv];
 703     sNeedsEnter = YES;
 704 
 705     NSPoint point = [self mapNSScreenPointToJavaWithOffset:sDraggingLocation];
 706     DLog3(@"  -> posting dragExit, point %f, %f", point.x, point.y);
 707     JNF_MEMBER_CACHE(dragExitMethod, CDragSourceContextPeerClass, "dragExit", "(II)V");
 708     JNFCallVoidMethod(env, fDragSourceContextPeer, dragExitMethod, (jint) point.x, (jint) point.y); // AWT_THREADING Safe (event)
 709 }
 710 
 711 
 712 // Java assumes that the origin is the top-left corner of the screen.
 713 // Cocoa assumes that the origin is the bottom-left corner of the screen.
 714 // Adjust the y coordinate to account for this.
 715 // NOTE: Also need to take into account the 0 screen relative screen coords.
 716 //  This is because all screen coords in Cocoa are relative to the 0 screen.
 717 // Also see +[CWindow convertAWTToCocoaScreenRect]
 718 // NSScreen-to-JavaScreen mapping:
 719 - (NSPoint) mapNSScreenPointToJavaWithOffset:(NSPoint)screenPoint {
 720     NSRect mainR = [[[NSScreen screens] objectAtIndex:0] frame];
 721     NSPoint point = NSMakePoint(screenPoint.x, mainR.size.height - (screenPoint.y));
 722 
 723     // Adjust the point with the drag image offset to get the real mouse hotspot:
 724     // The point should remain in screen coordinates (as per DragSourceEvent.getLocation() documentation)
 725     point.x -= fDragImageOffset.x;
 726     point.y -= ([fDragImage size].height + fDragImageOffset.y);
 727 
 728     return point;
 729 }
 730 
 731 @end