52f241a0640952f8c16ea49276eea9c4c7a9e1e8
[enjoyable.git] / TargetMouseMove.m
1 //
2 // TargetMouseMove.m
3 // Enjoy
4 //
5 // Created by Yifeng Huang on 7/26/12.
6 // Copyright (c) 2012 __MyCompanyName__. All rights reserved.
7 //
8
9 #import "TargetMouseMove.h"
10
11 #import "JoystickController.h"
12
13 @implementation TargetMouseMove {
14 int sign;
15 }
16
17 -(BOOL) isContinuous {
18 return YES;
19 }
20
21 + (NSString *)serializationCode {
22 return @"mmove";
23 }
24
25 - (NSDictionary *)serialize {
26 return @{ @"type": @"mmove", @"axis": @(_axis) };
27 }
28
29 + (Target *)targetDeserialize:(NSDictionary *)serialization
30 withConfigs:(NSArray *)configs {
31 TargetMouseMove *target = [[TargetMouseMove alloc] init];
32 target.axis = [serialization[@"axis"] intValue];
33 return target;
34 }
35
36 - (BOOL)update:(JoystickController *)jc {
37 if (fabsf(self.magnitude) < 0.01) {
38 sign = 0;
39 return NO; // dead zone
40 }
41
42 // If the action crossed over High/Low, this target is done.
43 if (!sign)
44 sign = self.magnitude < 0 ? -1 : 1;
45 else if (sign / self.magnitude < 0) {
46 sign = 0;
47 return NO;
48 }
49
50 NSRect screenRect = [[NSScreen mainScreen] frame];
51 CGFloat height = screenRect.size.height;
52
53 // TODO
54 float speed = 4.f;
55 if ([jc frontWindowOnly])
56 speed = 12.f;
57 float dx = 0.f, dy = 0.f;
58 if (_axis == 0)
59 dx = self.magnitude * speed;
60 else
61 dy = self.magnitude * speed;
62 NSPoint mouseLoc = jc.mouseLoc;
63 mouseLoc.x += dx;
64 mouseLoc.y -= dy;
65 jc.mouseLoc = mouseLoc;
66
67 CGEventRef move = CGEventCreateMouseEvent(NULL, kCGEventMouseMoved,
68 CGPointMake(mouseLoc.x, height - mouseLoc.y),
69 0);
70 CGEventSetType(move, kCGEventMouseMoved);
71 CGEventSetIntegerValueField(move, kCGMouseEventDeltaX, (int)dx);
72 CGEventSetIntegerValueField(move, kCGMouseEventDeltaY, (int)dy);
73
74 if ([jc frontWindowOnly]) {
75 ProcessSerialNumber psn;
76 GetFrontProcess(&psn);
77 CGEventPostToPSN(&psn, move);
78 }
79 else {
80 CGEventPost(kCGHIDEventTap, move);
81 }
82
83 CFRelease(move);
84 return YES;
85 }
86
87 @end