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