-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
CRobot.m
424 lines (365 loc) · 14.9 KB
/
CRobot.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
/*
* Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* 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.
*/
#import "JNIUtilities.h"
#import <ApplicationServices/ApplicationServices.h>
#import "CRobotKeyCode.h"
#import "LWCToolkit.h"
#import "sun_lwawt_macosx_CRobot.h"
#import "java_awt_event_InputEvent.h"
#import "java_awt_event_KeyEvent.h"
#import "sizecalc.h"
#import "ThreadUtilities.h"
// Starting number for event numbers generated by Robot.
// Apple docs don't mention at all what are the requirements
// for these numbers. It seems that they must be higher
// than event numbers from real events, which start at some
// value close to zero. There is no API for obtaining current
// event number, so we have to start from some random number.
// 32000 as starting value works for me, let's hope that it will
// work for others as well.
#define ROBOT_EVENT_NUMBER_START 32000
#define k_JAVA_ROBOT_WHEEL_COUNT 1
// In OS X, left and right mouse button share the same click count.
// That is, if one starts clicking the left button rapidly and then
// switches to the right button, then the click count will continue
// increasing, without dropping to 1 in between. The middle button,
// however, has its own click count.
// For robot, we aren't going to emulate all that complexity. All our
// synhtetic clicks share the same click count.
static int gsClickCount;
static NSTimeInterval gsLastClickTime;
// Apparently, for mouse up/down events we have to set an event number
// that is incremented on each button press. Otherwise, strange things
// happen with z-order.
static int gsEventNumber;
static int* gsButtonEventNumber;
static NSTimeInterval gNextKeyEventTime;
static inline CGKeyCode GetCGKeyCode(jint javaKeyCode);
static void PostMouseEvent(const CGPoint point, CGMouseButton button,
CGEventType type, int clickCount, int eventNumber);
static int GetClickCount(BOOL isDown);
static void
CreateJavaException(JNIEnv* env, CGError err)
{
// Throw a java exception indicating what is wrong.
NSString* s = [NSString stringWithFormat:@"Robot: CGError: %d", err];
(*env)->ThrowNew(env, (*env)->FindClass(env, "java/awt/AWTException"),
[s UTF8String]);
}
/**
* Saves the "safe moment" when the NEXT event can be posted by the robot safely
* and sleeps for some time if the "safe moment" for the CURRENT event is not
* reached.
*
* We need to sleep to give time for the macOS to update the state.
*
* The "mouse move" events are skipped, because it is not a big issue if we lost
* some of them, the latest coordinates are saved in the peer and will be used
* for clicks.
*/
static inline void autoDelay(BOOL isMove) {
if (!isMove){
NSTimeInterval now = [[NSDate date] timeIntervalSinceReferenceDate];
NSTimeInterval delay = gNextKeyEventTime - now;
if (delay > 0) {
[NSThread sleepForTimeInterval:delay];
}
}
gNextKeyEventTime = [[NSDate date] timeIntervalSinceReferenceDate] + 0.050;
}
/*
* Class: sun_lwawt_macosx_CRobot
* Method: initRobot
* Signature: (V)V
*/
JNIEXPORT void JNICALL
Java_sun_lwawt_macosx_CRobot_initRobot
(JNIEnv *env, jobject peer)
{
// Set things up to let our app act like a synthetic keyboard and mouse.
// Always set all states, in case Apple ever changes default behaviors.
static int setupDone = 0;
if (!setupDone) {
[ThreadUtilities performOnMainThreadWaiting:NO block:^(){
int i;
jint* tmp;
jboolean copy = JNI_FALSE;
setupDone = 1;
// Don't block local events after posting ours
CGSetLocalEventsSuppressionInterval(0.0);
// Let our event's modifier key state blend with local hardware events
CGEnableEventStateCombining(TRUE);
// Don't let our events block local hardware events
CGSetLocalEventsFilterDuringSupressionState(
kCGEventFilterMaskPermitAllEvents,
kCGEventSupressionStateSupressionInterval);
CGSetLocalEventsFilterDuringSupressionState(
kCGEventFilterMaskPermitAllEvents,
kCGEventSupressionStateRemoteMouseDrag);
gsClickCount = 0;
gsLastClickTime = 0;
gNextKeyEventTime = 0;
gsEventNumber = ROBOT_EVENT_NUMBER_START;
gsButtonEventNumber = (int*)SAFE_SIZE_ARRAY_ALLOC(malloc, sizeof(int), gNumberOfButtons);
if (gsButtonEventNumber == NULL) {
JNU_ThrowOutOfMemoryError(env, NULL);
return;
}
for (i = 0; i < gNumberOfButtons; ++i) {
gsButtonEventNumber[i] = ROBOT_EVENT_NUMBER_START;
}
}];
}
}
/*
* Class: sun_lwawt_macosx_CRobot
* Method: mouseEvent
* Signature: (IIIIZZ)V
*/
JNIEXPORT void JNICALL
Java_sun_lwawt_macosx_CRobot_mouseEvent
(JNIEnv *env, jobject peer, jint mouseLastX, jint mouseLastY, jint buttonsState,
jboolean isButtonsDownState, jboolean isMouseMove)
{
JNI_COCOA_ENTER(env);
autoDelay(isMouseMove);
// This is the native method called when Robot mouse events occur.
// The CRobot tracks the mouse position, and which button was
// pressed. The peer also tracks the mouse button desired state,
// the appropriate key modifier state, and whether the mouse action
// is simply a mouse move with no mouse button state changes.
// volatile, otherwise it warns that it might be clobbered by 'longjmp'
volatile CGPoint point;
point.x = mouseLastX;
point.y = mouseLastY;
__block CGMouseButton button = kCGMouseButtonLeft;
__block CGEventType type = kCGEventMouseMoved;
void (^HandleRobotButton)(CGMouseButton, CGEventType, CGEventType, CGEventType) =
^(CGMouseButton cgButton, CGEventType cgButtonUp, CGEventType cgButtonDown,
CGEventType cgButtonDragged) {
button = cgButton;
type = cgButtonUp;
if (isButtonsDownState) {
if (isMouseMove) {
type = cgButtonDragged;
} else {
type = cgButtonDown;
}
}
};
// Left
if (buttonsState & java_awt_event_InputEvent_BUTTON1_MASK ||
buttonsState & java_awt_event_InputEvent_BUTTON1_DOWN_MASK ) {
HandleRobotButton(kCGMouseButtonLeft, kCGEventLeftMouseUp,
kCGEventLeftMouseDown, kCGEventLeftMouseDragged);
}
// Other
if (buttonsState & java_awt_event_InputEvent_BUTTON2_MASK ||
buttonsState & java_awt_event_InputEvent_BUTTON2_DOWN_MASK ) {
HandleRobotButton(kCGMouseButtonCenter, kCGEventOtherMouseUp,
kCGEventOtherMouseDown, kCGEventOtherMouseDragged);
}
// Right
if (buttonsState & java_awt_event_InputEvent_BUTTON3_MASK ||
buttonsState & java_awt_event_InputEvent_BUTTON3_DOWN_MASK ) {
HandleRobotButton(kCGMouseButtonRight, kCGEventRightMouseUp,
kCGEventRightMouseDown, kCGEventRightMouseDragged);
}
// Extra
if (gNumberOfButtons > 3) {
int extraButton;
for (extraButton = 3; extraButton < gNumberOfButtons; ++extraButton) {
if ((buttonsState & gButtonDownMasks[extraButton])) {
HandleRobotButton(extraButton, kCGEventOtherMouseUp,
kCGEventOtherMouseDown, kCGEventOtherMouseDragged);
}
}
}
int clickCount = 0;
int eventNumber = gsEventNumber;
if (isMouseMove) {
// any mouse movement resets click count
gsLastClickTime = 0;
} else {
clickCount = GetClickCount(isButtonsDownState);
if (isButtonsDownState) {
gsButtonEventNumber[button] = gsEventNumber++;
}
eventNumber = gsButtonEventNumber[button];
}
PostMouseEvent(point, button, type, clickCount, eventNumber);
JNI_COCOA_EXIT(env);
}
/*
* Class: sun_lwawt_macosx_CRobot
* Method: mouseWheel
* Signature: (I)V
*/
JNIEXPORT void JNICALL
Java_sun_lwawt_macosx_CRobot_mouseWheel
(JNIEnv *env, jobject peer, jint wheelAmt)
{
autoDelay(NO);
[ThreadUtilities performOnMainThreadWaiting:YES block:^(){
CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateHIDSystemState);
CGEventRef event = CGEventCreateScrollWheelEvent(source,
kCGScrollEventUnitLine,
k_JAVA_ROBOT_WHEEL_COUNT, wheelAmt);
if (event != NULL) {
CGEventPost(kCGHIDEventTap, event);
CFRelease(event);
}
if (source != NULL) {
CFRelease(source);
}
}];
}
/*
* Class: sun_lwawt_macosx_CRobot
* Method: keyEvent
* Signature: (IZ)V
*/
JNIEXPORT void JNICALL
Java_sun_lwawt_macosx_CRobot_keyEvent
(JNIEnv *env, jobject peer, jint javaKeyCode, jboolean keyPressed)
{
autoDelay(NO);
[ThreadUtilities performOnMainThreadWaiting:YES block:^(){
CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateHIDSystemState);
CGKeyCode keyCode = GetCGKeyCode(javaKeyCode);
CGEventRef event = CGEventCreateKeyboardEvent(source, keyCode, keyPressed);
if (event != NULL) {
CGEventFlags flags = CGEventSourceFlagsState(kCGEventSourceStateHIDSystemState);
if ((flags & kCGEventFlagMaskSecondaryFn) != 0) {
flags ^= kCGEventFlagMaskSecondaryFn;
CGEventSetFlags(event, flags);
}
CGEventPost(kCGHIDEventTap, event);
CFRelease(event);
}
if (source != NULL) {
CFRelease(source);
}
}];
}
/*
* Class: sun_lwawt_macosx_CRobot
* Method: nativeGetScreenPixels
* Signature: (IIIII[I)V
*/
JNIEXPORT void JNICALL
Java_sun_lwawt_macosx_CRobot_nativeGetScreenPixels
(JNIEnv *env, jobject peer,
jint x, jint y, jint width, jint height, jdouble scale, jintArray pixels)
{
JNI_COCOA_ENTER(env);
jint picX = x;
jint picY = y;
jint picWidth = width;
jint picHeight = height;
jsize size = (*env)->GetArrayLength(env, pixels);
if (size < (long) picWidth * picHeight || picWidth < 0 || picHeight < 0) {
JNU_ThrowInternalError(env, "Invalid arguments to get screen pixels");
return;
}
CGRect screenRect = CGRectMake(picX / scale, picY / scale,
picWidth / scale, picHeight / scale);
CGImageRef screenPixelsImage = CGWindowListCreateImage(screenRect,
kCGWindowListOptionOnScreenOnly,
kCGNullWindowID, kCGWindowImageBestResolution);
if (screenPixelsImage == NULL) {
return;
}
// get a pointer to the Java int array
void *jPixelData = (*env)->GetPrimitiveArrayCritical(env, pixels, 0);
CHECK_NULL(jPixelData);
// create a graphics context around the Java int array
CGColorSpaceRef picColorSpace = CGColorSpaceCreateWithName(
kCGColorSpaceSRGB);
CGContextRef jPicContextRef = CGBitmapContextCreate(
jPixelData,
picWidth, picHeight,
8, picWidth * sizeof(jint),
picColorSpace,
kCGBitmapByteOrder32Host |
kCGImageAlphaNoneSkipFirst);
CGColorSpaceRelease(picColorSpace);
// flip, scale, and color correct the screen image into the Java pixels
CGRect bounds = { { 0, 0 }, { picWidth, picHeight } };
CGContextDrawImage(jPicContextRef, bounds, screenPixelsImage);
CGContextFlush(jPicContextRef);
// cleanup
CGContextRelease(jPicContextRef);
CGImageRelease(screenPixelsImage);
// release the Java int array back up to the JVM
(*env)->ReleasePrimitiveArrayCritical(env, pixels, jPixelData, 0);
JNI_COCOA_EXIT(env);
}
/****************************************************
* Helper methods
****************************************************/
static void PostMouseEvent(const CGPoint point, CGMouseButton button,
CGEventType type, int clickCount, int eventNumber)
{
[ThreadUtilities performOnMainThreadWaiting:YES block:^(){
CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateHIDSystemState);
CGEventRef mouseEvent = CGEventCreateMouseEvent(source, type, point, button);
if (mouseEvent != NULL) {
CGEventSetIntegerValueField(mouseEvent, kCGMouseEventClickState, clickCount);
CGEventSetIntegerValueField(mouseEvent, kCGMouseEventNumber, eventNumber);
CGEventPost(kCGHIDEventTap, mouseEvent);
CFRelease(mouseEvent);
}
if (source != NULL) {
CFRelease(source);
}
}];
}
static inline CGKeyCode GetCGKeyCode(jint javaKeyCode)
{
CRobotKeyCodeMapping *keyCodeMapping = [CRobotKeyCodeMapping sharedInstance];
return [keyCodeMapping getOSXKeyCodeForJavaKey:javaKeyCode];
}
static int GetClickCount(BOOL isDown) {
NSTimeInterval now = [[NSDate date] timeIntervalSinceReferenceDate];
NSTimeInterval clickInterval = now - gsLastClickTime;
BOOL isWithinTreshold = clickInterval < [NSEvent doubleClickInterval];
if (isDown) {
if (isWithinTreshold) {
gsClickCount++;
} else {
gsClickCount = 1;
}
gsLastClickTime = now;
} else {
// In OS X, a mouse up has the click count of the last mouse down
// if an interval between up and down is within the double click
// threshold, and 0 otherwise.
if (!isWithinTreshold) {
gsClickCount = 0;
}
}
return gsClickCount;
}