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