CDragSource.m revision 6099
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
//#define DND_DEBUG TRUE
#import "java_awt_dnd_DnDConstants.h"
#import <Cocoa/Cocoa.h>
#import "AWTEvent.h"
#import "AWTView.h"
#import "CDataTransferer.h"
#import "CDropTarget.h"
#import "CDragSource.h"
#import "DnDUtilities.h"
#import "ThreadUtilities.h"
// When sIsJavaDragging is true Java drag gesture has been recognized and a drag is/has been initialized.
// We must stop posting MouseEvent.MOUSE_DRAGGED events for the duration of the drag or all hell will break
// loose in shared code - tracking state going haywire.
static BOOL sIsJavaDragging;
@interface NSEvent(AWTAdditions)
+ (void)javaDraggingBegin;
+ (void)javaDraggingEnd;
@end
+ (void)javaDraggingBegin
{
}
+ (void)javaDraggingEnd
{
// sIsJavaDragging is reset on mouseDown as well.
}
@end
static NSDragOperation sDragOperation;
static NSPoint sDraggingLocation;
static CDragSource* sCurrentDragSource;
static BOOL sNeedsEnter;
+ (CDragSource *) currentDragSource {
return sCurrentDragSource;
}
- (id)init:(jobject)jdragsourcecontextpeer component:(jobject)jcomponent peer:(jobject)jpeer control:(id)control
dragPosX:(jint)dragPosX dragPosY:(jint)dragPosY modifiers:(jint)extModifiers clickCount:(jint)clickCount
dragImage:(jobject)jnsdragimage dragImageOffsetX:(jint)jdragimageoffsetx dragImageOffsetY:(jint)jdragimageoffsety
{
fComponent = nil;
// Construct the object if we have a valid model for it:
if (jnsdragimage) {
[fDragImage retain];
}
// Set this object as a dragging source:
// Let AWTEvent know Java drag is getting underway:
}
else {
}
return self;
}
{
// Remove this dragging source from the view:
// Clean up JNI refs
if (fComponent != NULL) {
fComponent = NULL;
}
if (fComponentPeer != NULL) {
}
if (fDragSourceContextPeer != NULL) {
}
if (fTransferable != NULL) {
}
if (fTriggerEvent != NULL) {
}
}
}
if (fFormatMap != NULL) {
fFormatMap = NULL;
}
}
- (void)dealloc
{
// Delete or release local data:
fDragImage = nil;
[super dealloc];
}
//- (void)finalize { [super finalize]; }
// Appropriated from Windows' awt_DataTransferer.cpp:
//
// * NOTE: This returns a JNI Local Ref. Any code that calls must call DeleteLocalRef with the return value.
//
{
JNF_STATIC_MEMBER_CACHE(getInstanceMethod, DataTransfererClass, "getInstance", "()Lsun/awt/datatransfer/DataTransferer;");
}
// Appropriated from Windows' awt_DataTransferer.cpp:
//
// * NOTE: This returns a JNI Local Ref. Any code that calls must call DeleteLocalRef with the return value.
//
{
if (transferer != NULL) {
JNF_MEMBER_CACHE(convertDataMethod, DataTransfererClass, "convertData", "(Ljava/lang/Object;Ljava/awt/datatransfer/Transferable;JLjava/util/Map;Z)[B");
data = JNFCallObjectMethod(env, transferer, convertDataMethod, fComponent, fTransferable, format, fFormatMap, (jboolean) TRUE);
}
return data;
}
// Encodes a byte array of zero-terminated filenames into an NSArray of NSStrings representing them.
// Borrowed and adapted from awt_DataTransferer.c, convertFileType().
{
jsize i;
// Get number of filenames while making sure to skip over empty strings.
for (i = 1; i < jbytesLength; i++) {
strings++;
}
// Create the file list to return:
for (i = 0; i < jbytesLength; i++) {
// Skip over empty strings:
continue;
}
// Update the position marker:
// Add this filename to the file list:
// Decompose the filename
}
// 03-01-09 Note: keep this around for debugging.
}
// Set up the pasteboard for dragging:
// 9-20-02 Note: leave this here for debugging:
//[pb declareTypes: [NSArray arrayWithObject: NSStringPboardType] owner: self];
//return TRUE;
// Get byte array elements:
return FALSE;
// Allocate storage arrays for dragging types to register with the pasteboard:
// And assume there are no NS-type data: [Radar 3065621]
// This is to be able to drop transferables containing only a serialized object flavor, e.g.:
// "JAVA_DATAFLAVOR:application/x-java-serialized-object; class=java.awt.Label".
BOOL hasNSTypeData = false;
// Collect all supported types in a pasteboard format into the storage arrays:
jsize i;
for (i = 0; i < formatsLength; i++) {
if (jformat >= 0) {
// Add element type to the storage array.
// This is a good approximation if not perfect. A conclusive search would
// have to be done matching all defined strings in AppKit's commonStrings.h.
hasNSTypeData = true;
}
}
}
}
// 1-16-03 Note: [Radar 3065621]
// When TransferHandler is used with Swing components it puts only a type like this on the pasteboard:
// "JAVA_DATAFLAVOR:application/x-java-jvm-local-objectref; class=java.lang.String"
// And there's similar type for serialized object only transferables.
// Since our drop targets aren't trained for arbitrary data types yet we need to fake an empty string
// which will cause drop target handlers to fire.
// KCH - 3550405 If the drag is between Swing components, formatsLength == 0, so expand the check.
// Also, use a custom format rather than NSString, since that will prevent random views from accepting the drag
}
// Declare pasteboard types. If the types array is empty we still want to declare them
// KCH - Lame conversion bug between Cocoa and Carbon drag types
// If I provide the filenames _right now_, NSFilenamesPboardType is properly converted to CoreDrag flavors
// If I try to wait until pasteboard:provideDataForType:, the conversion won't happen
// and pasteboard:provideDataForType: won't even get called! (unless I go over a Cocoa app)
}
}
// This is an NSPasteboard callback. In declareTypesToPasteboard:withEnv:, we only declared the types
// When the AppKit DnD system actually needs the data, this method will be invoked.
// Note that if the transfer is handled entirely from Swing (as in a local-vm drag), this method may never be called.
// 9-20-02 Note: leave this here for debugging:
//[pb setString: @"Hello, World!" forType: NSStringPboardType];
// return;
// Set up Java environment:
// Collect data in a pasteboard format:
if (jformat >= 0) {
// Convert DataTransfer data to a Java byte array:
// Note that this will eventually call getTransferData()
// Get element data to the storage array. For NSFilenamesPboardType type we use
// an NSArray-type data - NSData-type data would cause a crash.
}
}
}
}
// If we are the custom type that matches local-vm drags, set an empty NSData
}
// Add pasteboard data for the type:
// Remember, NSFilenamesPboardType's data is NSArray (property list), not NSData!
// We must use proper pb accessor depending on the data type.
else
}
- (void)validateDragImage
{
// Make a small blank image if we don't have a drag image:
if (fDragImage == nil) {
// 9-30-02 Note: keep this around for debugging:
}
}
{
// Get NSView for the drag source:
// Convert mouse coordinates to NS:
// Convert fTriggerEventTimeStamp to NS - AWTEvent.h defines UTC(nsEvent) as ((jlong)[event timestamp] * 1000):
// Convert fModifiers (extModifiers) to NS:
float pressure = 0.0;
if (isDrag) {
pressure = 1.0;
} else {
}
// Convert fModifiers (extModifiers) to NS:
// Just a dummy value ...
// Make a native autoreleased dragging event:
return dragEvent;
}
- (void)doDrag
{
// Set up Java environment:
// Set up the pasteboard:
// Make a native autoreleased NS dragging event:
// Get NSView for the drag source:
// Make sure we have a valid drag image:
// Get drag origin and offset:
dragOrigin.x += fDragImageOffset.x;
// Drag offset values don't seem to matter:
// These variables should be set based on the transferable:
DLog5(@" - drag image: %f, %f (%f x %f)", fDragImageOffset.x, fDragImageOffset.y, [dragImage size].width, [dragImage size].height);
DLog3(@" - event point (window) %f, %f", [dragEvent locationInWindow].x, [dragEvent locationInWindow].y);
// Set up the fDragKeyModifier, so we know if the operation has changed
// Set up the fDragMouseModifier, so we can |= it later (since CoreDrag doesn't tell us mouse states during a drag)
// Set the current DragSource
sNeedsEnter = YES;
@try {
// Data dragging:
if (isFileDrag == FALSE) {
[view dragImage:dragImage at:dragOrigin offset:dragOffset event:dragEvent pasteboard:pb source:view slideBack:YES];
} else if (fileDragPromises == FALSE) {
// File dragging:
NSLog(@"[CDragSource drag]: file dragging is unsupported.");
}
} else {
// Promised file dragging:
NSLog(@"[CDragSource drag]: file dragging promises are unsupported.");
BOOL success = [view dragPromisedFilesOfTypes:fileTypesArray fromRect:fileLocationRect source:view slideBack:YES event:dragEvent];
}
}
// Convert drag operation to Java:
// Drag success must acount for DragOperationNone:
// We have a problem here... we don't send DragSource dragEnter/Exit messages outside of our own process
// This means that if you drag outside of the app and drop, even if it's valid, a dragDropFinished is posted without dragEnter
// I'm worried that this might confuse Java, so we're going to send a "bogus" dragEnter if necessary (only if the drag succeeded)
if (success && sNeedsEnter) {
}
// DragSourceContextPeer.dragDropFinished() should be called even if there was an error:
JNF_MEMBER_CACHE(dragDropFinishedMethod, CDragSourceContextPeerClass, "dragDropFinished", "(ZIII)V");
JNFCallVoidMethod(env, fDragSourceContextPeer, dragDropFinishedMethod, success, dragOp, (jint) point.x, (jint) point.y); // AWT_THREADING Safe (event)
} @finally {
// Clear the current DragSource
sNeedsEnter = NO;
}
// We have to do this, otherwise AppKit doesn't know we're finished dragging. Yup, it's that bad.
}
}
- (void)drag
{
// Set the drag cursor (or not 3839999)
//JNIEnv *env = [ThreadUtilities getJNIEnv];
//jobject gCursor = JNFNewGlobalRef(env, fCursor);
//[EventFactory setJavaCursor:gCursor withEnv:env];
[self performSelectorOnMainThread:@selector(doDrag) withObject:nil waitUntilDone:YES]; // AWT_THREADING Safe (called from unique asynchronous thread)
}
/******************************** BEGIN NSDraggingSource Interface ********************************/
//DLog2(@"[CDragSource draggingOperationChanged]: %@\n", self);
if ([CDropTarget currentDropTarget]) targetActions = [[CDropTarget currentDropTarget] currentJavaActions];
jint modifiedModifiers = fDragKeyModifiers | fDragMouseModifiers | [DnDUtilities javaKeyModifiersForNSDragOperation:dragOp];
JNF_MEMBER_CACHE(operationChangedMethod, CDragSourceContextPeerClass, "operationChanged", "(IIII)V");
JNFCallVoidMethod(env, fDragSourceContextPeer, operationChangedMethod, targetActions, modifiedModifiers, (jint) point.x, (jint) point.y); // AWT_THREADING Safe (event)
}
//DLog2(@"[CDragSource draggingSourceOperationMaskForLocal]: %@\n", self);
}
/* 9-16-02 Note: we don't support promises yet.
- (NSArray *)namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination {
}*/
// Initialize static variables:
}
- (void)draggedImage:(NSImage *)image endedAt:(NSPoint)screenPoint operation:(NSDragOperation)operation {
}
//DLog4(@"[CDragSource draggedImage moved]: (%d, %d) %@\n", (int) screenPoint.x, (int) screenPoint.y, self);
// There are two things we would be interested in:
// a) mouse pointer has moved
// b) drag actions (key modifiers) have changed
// a) mouse pointer has moved:
//DLog2(@"[CDragSource draggedImage:movedTo]: mouse moved, %@\n", self);
notifyJava = TRUE;
}
// b) drag actions (key modifiers) have changed:
if (fDragKeyModifiers != modifiers) {
if (sDragOperation != allowedOp) {
}
}
// Should we notify Java things have changed?
if (notifyJava) {
if ([CDropTarget currentDropTarget]) targetActions = [[CDropTarget currentDropTarget] currentJavaActions];
// Motion: dragMotion, dragMouseMoved
JNFCallVoidMethod(env, fDragSourceContextPeer, dragMotionMethod, targetActions, (jint) fModifiers, (jint) point.x, (jint) point.y); // AWT_THREADING Safe (event)
JNFCallVoidMethod(env, fDragSourceContextPeer, dragMouseMovedMethod, targetActions, (jint) fModifiers, (jint) point.x, (jint) point.y); // AWT_THREADING Safe (event)
}
}
//DLog2(@"[CDragSource ignoreModifierKeysWhileDragging]: %@\n", self);
return NO;
}
/******************************** END NSDraggingSource Interface ********************************/
// postDragEnter and postDragExit are called from CDropTarget when possible and appropriate
// Currently only possible if source and target are in the same process
- (void) postDragEnter {
sNeedsEnter = NO;
if ([CDropTarget currentDropTarget]) targetActions = [[CDropTarget currentDropTarget] currentJavaActions];
JNFCallVoidMethod(env, fDragSourceContextPeer, dragEnterMethod, targetActions, (jint) fModifiers, (jint) point.x, (jint) point.y); // AWT_THREADING Safe (event)
}
- (void) postDragExit {
sNeedsEnter = YES;
JNFCallVoidMethod(env, fDragSourceContextPeer, dragExitMethod, (jint) point.x, (jint) point.y); // AWT_THREADING Safe (event)
}
// Java assumes that the origin is the top-left corner of the screen.
// Cocoa assumes that the origin is the bottom-left corner of the screen.
// Adjust the y coordinate to account for this.
// NOTE: Also need to take into account the 0 screen relative screen coords.
// This is because all screen coords in Cocoa are relative to the 0 screen.
// Also see +[CWindow convertAWTToCocoaScreenRect]
// NSScreen-to-JavaScreen mapping:
// Adjust the point with the drag image offset to get the real mouse hotspot:
// The point should remain in screen coordinates (as per DragSourceEvent.getLocation() documentation)
point.x -= fDragImageOffset.x;
return point;
}
@end