Have device controller setup itself rather than relying on the application delegate...
[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 "NJDeviceController.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 *)outputDeserialize:(NSDictionary *)serialization
26 withMappings:(NSArray *)mappings {
27 NJOutputMouseMove *output = [[NJOutputMouseMove alloc] init];
28 output.axis = [serialization[@"axis"] intValue];
29 output.speed = [serialization[@"speed"] floatValue];
30 if (!output.speed)
31 output.speed = 10;
32 return output;
33 }
34
35 - (BOOL)isContinuous {
36 return YES;
37 }
38
39 #define CLAMP(a, l, h) MIN(h, MAX(a, l))
40
41 - (BOOL)update:(NJDeviceController *)jc {
42 if (self.magnitude < 0.05)
43 return NO; // dead zone
44
45 CGSize size = NSScreen.mainScreen.frame.size;
46
47 CGFloat dx = 0, dy = 0;
48 switch (_axis) {
49 case 0:
50 dx = -self.magnitude * _speed;
51 break;
52 case 1:
53 dx = self.magnitude * _speed;
54 break;
55 case 2:
56 dy = -self.magnitude * _speed;
57 break;
58 case 3:
59 dy = self.magnitude * _speed;
60 break;
61 }
62 NSPoint mouseLoc = jc.mouseLoc;
63 mouseLoc.x = CLAMP(mouseLoc.x + dx, 0, size.width - 1);
64 mouseLoc.y = CLAMP(mouseLoc.y - dy, 0, size.height - 1);
65 jc.mouseLoc = mouseLoc;
66
67 CGEventRef move = CGEventCreateMouseEvent(NULL, kCGEventMouseMoved,
68 CGPointMake(mouseLoc.x, size.height - mouseLoc.y),
69 0);
70 CGEventSetIntegerValueField(move, kCGMouseEventDeltaX, (int)dx);
71 CGEventSetIntegerValueField(move, kCGMouseEventDeltaY, (int)dy);
72 CGEventPost(kCGHIDEventTap, move);
73
74 if (CGEventSourceButtonState(kCGEventSourceStateHIDSystemState, kCGMouseButtonLeft)) {
75 CGEventSetType(move, kCGEventLeftMouseDragged);
76 CGEventSetIntegerValueField(move, kCGMouseEventButtonNumber, kCGMouseButtonLeft);
77 CGEventPost(kCGHIDEventTap, move);
78 }
79 if (CGEventSourceButtonState(kCGEventSourceStateHIDSystemState, kCGMouseButtonRight)) {
80 CGEventSetType(move, kCGEventRightMouseDragged);
81 CGEventSetIntegerValueField(move, kCGMouseEventButtonNumber, kCGMouseButtonRight);
82 CGEventPost(kCGHIDEventTap, move);
83 }
84 if (CGEventSourceButtonState(kCGEventSourceStateHIDSystemState, kCGMouseButtonCenter)) {
85 CGEventSetType(move, kCGEventOtherMouseDragged);
86 CGEventSetIntegerValueField(move, kCGMouseEventButtonNumber, kCGMouseButtonCenter);
87 CGEventPost(kCGHIDEventTap, move);
88 }
89
90 CFRelease(move);
91 return YES;
92 }
93
94 @end