Remove website, now in yukkurigames.com repository.
[enjoyable.git] / Classes / NJOutputMouseButton.m
1 //
2 // NJOutputMouseButton.m
3 // Enjoy
4 //
5 // Created by Yifeng Huang on 7/27/12.
6 //
7
8 #import "NJOutputMouseButton.h"
9
10 @implementation NJOutputMouseButton {
11 NSDate *upTime;
12 int clickCount;
13 NSPoint clickPosition;
14 }
15
16 + (NSTimeInterval)doubleClickInterval {
17 static NSTimeInterval s_doubleClickThreshold;
18 if (!s_doubleClickThreshold) {
19 s_doubleClickThreshold = [[NSUserDefaults.standardUserDefaults
20 objectForKey:@"com.apple.mouse.doubleClickThreshold"] floatValue];
21 if (s_doubleClickThreshold <= 0)
22 s_doubleClickThreshold = 1.0;
23 }
24 return s_doubleClickThreshold;
25 }
26
27 + (NSDate *)dateWithClickInterval {
28 return [[NSDate alloc] initWithTimeIntervalSinceNow:self.doubleClickInterval];
29 }
30
31 + (NSString *)serializationCode {
32 return @"mouse button";
33 }
34
35 - (NSDictionary *)serialize {
36 return @{ @"type": self.class.serializationCode, @"button": @(_button) };
37 }
38
39 + (NJOutput *)outputWithSerialization:(NSDictionary *)serialization {
40 NJOutputMouseButton *output = [[NJOutputMouseButton alloc] init];
41 output.button = [serialization[@"button"] intValue];
42 return output;
43 }
44
45 - (void)trigger {
46 CGFloat height = NSScreen.mainScreen.frame.size.height;
47 NSPoint mouseLoc = NSEvent.mouseLocation;
48 CGEventType eventType = _button == kCGMouseButtonLeft ? kCGEventLeftMouseDown
49 : _button == kCGMouseButtonRight ? kCGEventRightMouseDown
50 : kCGEventOtherMouseDown;
51 CGEventRef click = CGEventCreateMouseEvent(NULL,
52 eventType,
53 CGPointMake(mouseLoc.x, height - mouseLoc.y),
54 _button);
55
56 if (clickCount >= 3 || [upTime compare:[NSDate date]] == NSOrderedAscending
57 || !CGPointEqualToPoint(mouseLoc, clickPosition))
58 clickCount = 1;
59 else
60 ++clickCount;
61 CGEventSetIntegerValueField(click, kCGMouseEventClickState, clickCount);
62 CGEventPost(kCGHIDEventTap, click);
63 CFRelease(click);
64 clickPosition = mouseLoc;
65 }
66
67 - (void)untrigger {
68 upTime = [NJOutputMouseButton dateWithClickInterval];
69 NSPoint mouseLoc = NSEvent.mouseLocation;
70 CGFloat height = NSScreen.mainScreen.frame.size.height;
71 CGEventType eventType = _button == kCGMouseButtonLeft ? kCGEventLeftMouseUp
72 : _button == kCGMouseButtonRight ? kCGEventRightMouseUp
73 : kCGEventOtherMouseUp;
74 CGEventRef click = CGEventCreateMouseEvent(NULL,
75 eventType,
76 CGPointMake(mouseLoc.x, height - mouseLoc.y),
77 _button);
78 CGEventSetIntegerValueField(click, kCGMouseEventClickState, clickCount);
79 CGEventPost(kCGHIDEventTap, click);
80 CFRelease(click);
81 }
82
83 @end