More better names.
[enjoyable.git] / Classes / NJOutputMouseMove.m
1 //
2 // NJOutputMouseMove.m
3 // Enjoy
4 //
5 // Created by Yifeng Huang on 7/26/12.
6 //
7
8 #import "NJOutputMouseMove.h"
9
10 #import "NJInputController.h"
11
12 @implementation NJOutputMouseMove
13
14 + (NSString *)serializationCode {
15 return @"mouse move";
16 }
17
18 - (NSDictionary *)serialize {
19 return @{ @"type": self.class.serializationCode,
20 @"axis": @(_axis),
21 @"speed": @(_speed),
22 };
23 }
24
25 + (NJOutput *)outputWithSerialization:(NSDictionary *)serialization {
26 NJOutputMouseMove *output = [[NJOutputMouseMove alloc] init];
27 output.axis = [serialization[@"axis"] intValue];
28 output.speed = [serialization[@"speed"] floatValue];
29 if (!output.speed)
30 output.speed = 10;
31 return output;
32 }
33
34 - (BOOL)isContinuous {
35 return YES;
36 }
37
38 #define CLAMP(a, l, h) MIN(h, MAX(a, l))
39
40 - (BOOL)update:(NJInputController *)ic {
41 if (self.magnitude < 0.05)
42 return NO; // dead zone
43
44 CGSize size = NSScreen.mainScreen.frame.size;
45
46 CGFloat dx = 0, dy = 0;
47 switch (_axis) {
48 case 0:
49 dx = -self.magnitude * _speed;
50 break;
51 case 1:
52 dx = self.magnitude * _speed;
53 break;
54 case 2:
55 dy = -self.magnitude * _speed;
56 break;
57 case 3:
58 dy = self.magnitude * _speed;
59 break;
60 }
61 NSPoint mouseLoc = ic.mouseLoc;
62 mouseLoc.x = CLAMP(mouseLoc.x + dx, 0, size.width - 1);
63 mouseLoc.y = CLAMP(mouseLoc.y - dy, 0, size.height - 1);
64 ic.mouseLoc = mouseLoc;
65
66 CGEventRef move = CGEventCreateMouseEvent(NULL, kCGEventMouseMoved,
67 CGPointMake(mouseLoc.x, size.height - mouseLoc.y),
68 0);
69 CGEventSetIntegerValueField(move, kCGMouseEventDeltaX, (int)dx);
70 CGEventSetIntegerValueField(move, kCGMouseEventDeltaY, (int)dy);
71 CGEventPost(kCGHIDEventTap, move);
72
73 if (CGEventSourceButtonState(kCGEventSourceStateHIDSystemState, kCGMouseButtonLeft)) {
74 CGEventSetType(move, kCGEventLeftMouseDragged);
75 CGEventSetIntegerValueField(move, kCGMouseEventButtonNumber, kCGMouseButtonLeft);
76 CGEventPost(kCGHIDEventTap, move);
77 }
78 if (CGEventSourceButtonState(kCGEventSourceStateHIDSystemState, kCGMouseButtonRight)) {
79 CGEventSetType(move, kCGEventRightMouseDragged);
80 CGEventSetIntegerValueField(move, kCGMouseEventButtonNumber, kCGMouseButtonRight);
81 CGEventPost(kCGHIDEventTap, move);
82 }
83 if (CGEventSourceButtonState(kCGEventSourceStateHIDSystemState, kCGMouseButtonCenter)) {
84 CGEventSetType(move, kCGEventOtherMouseDragged);
85 CGEventSetIntegerValueField(move, kCGMouseEventButtonNumber, kCGMouseButtonCenter);
86 CGEventPost(kCGHIDEventTap, move);
87 }
88
89 CFRelease(move);
90 return YES;
91 }
92
93 @end