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