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