Show an error message if opening input devices fail. Move real vs. configuration...
[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 true;
19 }
20
21 @synthesize dir;
22
23 + (NSString *)serializationCode {
24 return @"mmove";
25 }
26
27 - (NSDictionary *)serialize {
28 return @{ @"type": @"mmove", @"dir": @(self.dir) };
29 }
30
31 + (Target *)targetDeserialize:(NSDictionary *)serialization
32 withConfigs:(NSArray *)configs {
33 TargetMouseMove *target = [[TargetMouseMove alloc] init];
34 target.dir = [serialization[@"dir"] intValue];
35 return target;
36 }
37
38 - (BOOL)update:(JoystickController *)jc {
39 if (fabsf(self.magnitude) < 0.01) {
40 sign = 0;
41 return NO; // dead zone
42 }
43
44 // If the action crossed over High/Low, this target is done.
45 if (!sign)
46 sign = self.magnitude < 0 ? -1 : 1;
47 else if (sign / self.magnitude < 0) {
48 sign = 0;
49 return NO;
50 }
51
52 NSRect screenRect = [[NSScreen mainScreen] frame];
53 NSInteger height = screenRect.size.height;
54
55 // TODO
56 float speed = 4.f;
57 if ([jc frontWindowOnly])
58 speed = 12.f;
59 float dx = 0.f, dy = 0.f;
60 if (self.dir == 0)
61 dx = self.magnitude * speed;
62 else
63 dy = self.magnitude * speed;
64 NSPoint mouseLoc = jc.mouseLoc;
65 mouseLoc.x += dx;
66 mouseLoc.y -= dy;
67 jc.mouseLoc = mouseLoc;
68
69 CGEventRef move = CGEventCreateMouseEvent(NULL, kCGEventMouseMoved,
70 CGPointMake(mouseLoc.x, height - mouseLoc.y),
71 0);
72 CGEventSetType(move, kCGEventMouseMoved);
73 CGEventSetIntegerValueField(move, kCGMouseEventDeltaX, dx);
74 CGEventSetIntegerValueField(move, kCGMouseEventDeltaY, dy);
75
76 if ([jc frontWindowOnly]) {
77 ProcessSerialNumber psn;
78 GetFrontProcess(&psn);
79 CGEventPostToPSN(&psn, move);
80 }
81 else {
82 CGEventPost(kCGHIDEventTap, move);
83 }
84
85 CFRelease(move);
86 return YES;
87 }
88
89 @end