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