-
Notifications
You must be signed in to change notification settings - Fork 0
/
WKHotKeyAssignment.m
385 lines (306 loc) · 9.36 KB
/
WKHotKeyAssignment.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
//
// WKHotKeyAssignment.m
// WhatKeys
//
// Created by Andy Lee on 7/6/10.
// Feel free to use this code however you like.
//
#import "WKHotKeyAssignment.h"
#import "DDHotKeyCenter.h"
// A category declaring methods that we want to treat as if they were private to this class.
// Objective-C does not have true private methods. Using a category in the .m like this is
// a convention for helping us treat methods _as if_ they were private, by not exposing them
// in the header.
@interface WKHotKeyAssignment ()
@property (readwrite, retain) NSAppleScript * compiledAppleScript;
- (NSError *)_errorWithMessage:(NSString *)errorMessage;
- (NSError *)_performPathAction;
- (NSError *)_performEmbeddedScriptAction;
@end
@implementation WKHotKeyAssignment
@synthesize name, keyCode, keyFlags, actionType, pathToAppleScript, embeddedAppleScript, compiledAppleScript;
@dynamic keyComboDisplayString;
#pragma mark -
#pragma mark Factory methods
+ (id)assignmentWithName:(NSString *)theName
keyCode:(NSInteger)theKeyCode
modifierFlags:(NSUInteger)theModifierFlags
pathToAppleScript:(NSString *)thePath
{
WKHotKeyAssignment * ka = [[[[self class] alloc] init] autorelease];
[ka setName:theName];
[ka setKeyCode:theKeyCode];
[ka setKeyFlags:theModifierFlags];
[ka setActionType:WKPathToAppleScriptActionType];
[ka setPathToAppleScript:thePath];
return ka;
}
+ (id)assignmentWithName:(NSString *)theName
keyCode:(NSInteger)theKeyCode
modifierFlags:(NSUInteger)theModifierFlags
AppleScript:(NSString *)theAppleScript
{
WKHotKeyAssignment * ka = [[[[self class] alloc] init] autorelease];
[ka setName:theName];
[ka setKeyCode:theKeyCode];
[ka setKeyFlags:theModifierFlags];
[ka setActionType:WKEmbeddedAppleScriptActionType];
[ka setEmbeddedAppleScript:theAppleScript];
return ka;
}
#pragma mark -
#pragma mark Init/awake/dealloc
- (id)init
{
self = [super init];
if (self)
{
hotKeyCenter = [[DDHotKeyCenter alloc] init];
name = @"Untitled";
keyCode = WKNoKeyCode;
keyFlags = WKNoKeyFlags;
actionType = WKEmbeddedAppleScriptActionType;
pathToAppleScript = @"";
embeddedAppleScript = @"beep";
compiledAppleScript = nil;
// Use KVO to observe values that should cause us to recompute compiledAppleScript.
[self addObserver:self forKeyPath:@"actionType" options:0 context:NULL];
[self addObserver:self forKeyPath:@"pathToAppleScript" options:0 context:NULL];
[self addObserver:self forKeyPath:@"embeddedAppleScript" options:0 context:NULL];
}
return self;
}
- (void)dealloc
{
// Stop observing things by KVO, since the things we observe have weak references to us.
[self removeObserver:self forKeyPath:@"actionType"];
[self removeObserver:self forKeyPath:@"pathToAppleScript"];
[self removeObserver:self forKeyPath:@"embeddedAppleScript"];
// Release ivars for which we have strong references.
[hotKeyCenter release];
[name release];
[pathToAppleScript release];
[embeddedAppleScript release];
[compiledAppleScript release];
[super dealloc];
}
#pragma mark -
#pragma mark Accessors
- (NSString *)keyComboDisplayString
{
if (keyCode == WKNoKeyCode)
{
return @"";
}
else
{
return SRStringForCocoaModifierFlagsAndKeyCode(keyFlags, keyCode);
}
}
#pragma mark -
#pragma mark Converting to and from plists
+ (NSArray *)assignmentsFromPlistArray:(NSArray *)arrayOfDicts
{
NSMutableArray * keyAssignments = [NSMutableArray array];
for (NSDictionary * dict in arrayOfDicts)
{
WKHotKeyAssignment * ka = [[[self alloc] init] autorelease];
[ka setValuesForKeysWithDictionary:dict];
[keyAssignments addObject:ka];
}
return keyAssignments;
}
+ (NSArray *)plistArrayFromAssignments:(NSArray *)arrayOfAssignments
{
NSMutableArray * plistArray = [NSMutableArray array];
for (WKHotKeyAssignment * ka in arrayOfAssignments)
{
[plistArray addObject:[ka dictionaryWithValuesForKeys:[NSArray arrayWithObjects:
@"name",
@"keyCode",
@"keyFlags",
@"actionType",
@"pathToAppleScript",
@"embeddedAppleScript",
nil]]];
}
return plistArray;
}
#pragma mark -
#pragma mark Managing hotkey actions
- (BOOL)registerHotKeyAction
{
BOOL ok = [hotKeyCenter registerHotKeyWithKeyCode:keyCode
modifierFlags:keyFlags
target:self
action:@selector(_handleHotkeyWithEvent:)
object:nil];
if (!ok)
{
NSLog(@"failed to register hotkey %@", [self keyComboDisplayString]);
}
return ok;
}
- (void)unregisterHotKeyAction
{
[hotKeyCenter unregisterHotKeysWithTarget:self];
}
- (NSError *)performHotKeyAction
{
NSError * error = nil;
if (actionType == WKPathToAppleScriptActionType)
{
error = [self _performPathAction];
}
else if (actionType == WKEmbeddedAppleScriptActionType)
{
error = [self _performEmbeddedScriptAction];
}
else
{
NSString * errorMessage = [NSString stringWithFormat:@"Unexpected value for action type: %d.", actionType];
error = [self _errorWithMessage:errorMessage];
}
if (error != nil)
{
NSLog(@"ERROR performing hotkey action: %@", error);
}
return error;
}
#pragma mark -
#pragma mark NSKeyValueObserving methods
+ (NSSet *)keyPathsForValuesAffectingKeyComboDisplayString
{
return [NSSet setWithObjects:@"keyCode", @"keyFlags", nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:@"actionType"]
|| [keyPath isEqualToString:@"pathToAppleScript"]
|| [keyPath isEqualToString:@"embeddedAppleScript"])
{
// Force compiledAppleScript to be recreated.
[self setCompiledAppleScript:nil];
}
else
{
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
#pragma mark -
#pragma mark NSObject methods
// In case you're ever debugging or just exploring and you ever use NSLog to print
// a WKHotKeyAssignment, this override of the description method provides more helpful
// information than the default implementation. (NSLog calls the description method
// when it prints an object.)
- (NSString *)description
{
NSString * actionText = nil;
if (actionType == WKPathToAppleScriptActionType)
{
actionText = [NSString stringWithFormat:@"path:'%@'", pathToAppleScript];
}
else if (actionType == WKEmbeddedAppleScriptActionType)
{
NSArray * lines = [embeddedAppleScript componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
if ([lines count] > 1)
{
actionText = [NSString stringWithFormat:@"script: %@...", [lines objectAtIndex:0]];
}
else
{
actionText = [NSString stringWithFormat:@"script: %@", embeddedAppleScript];
}
}
else
{
actionText = [NSString stringWithFormat:@"unexpected action type %d", actionType];
}
return [NSString stringWithFormat:@"<%@ -- %@>", [self keyComboDisplayString], actionText];
}
#pragma mark -
#pragma mark Private methods
- (void)_handleHotkeyWithEvent:(NSEvent *)event
{
[self performHotKeyAction];
}
- (NSError *)_errorWithDict:(NSDictionary *)errorDict
{
return [NSError errorWithDomain:@"WhatKeys" code:0 userInfo:errorDict];
}
- (NSError *)_errorWithMessage:(NSString *)errorMessage
{
return [self _errorWithDict:[NSDictionary dictionaryWithObjectsAndKeys:
errorMessage, NSLocalizedDescriptionKey,
nil]];
}
- (NSError *)_performAppleScript:(NSAppleScript *)script
{
NSDictionary * errorDict = nil;
NSAppleEventDescriptor * scriptResult = [script executeAndReturnError:&errorDict];
if (scriptResult == nil)
{
NSLog(@"ERROR performing AppleScript: %@", errorDict);
return [self _errorWithMessage:[errorDict objectForKey:NSAppleScriptErrorMessage]];
}
else
{
return nil;
}
}
- (NSError *)_performPathAction
{
// Handle case where the script path is unspecified or invalid.
if (pathToAppleScript == nil)
{
return [self _errorWithMessage:@"No script path was specified."];
}
NSURL * scriptURL = [NSURL fileURLWithPath:pathToAppleScript];
if (scriptURL == nil)
{
return [self _errorWithMessage:[NSString stringWithFormat:@"Invalid script path: '%@'.", pathToAppleScript]];
}
// Try to load the script if we haven't already.
if (compiledAppleScript == nil)
{
NSDictionary * errorDict = nil;
NSAppleScript * script = [[[NSAppleScript alloc] initWithContentsOfURL:scriptURL error:&errorDict] autorelease];
if (script == nil)
{
return [self _errorWithDict:errorDict];
}
if (![script compileAndReturnError:&errorDict])
{
return [self _errorWithDict:errorDict];
}
[self setCompiledAppleScript:script];
}
// Try to execute the script.
return [self _performAppleScript:compiledAppleScript];
}
- (NSError *)_performEmbeddedScriptAction
{
// Handle the case where the script is unspecified.
if ([embeddedAppleScript length] == 0)
{
return [self _errorWithMessage:@"No script was specified."];
}
// Try to load the script if we haven't already.
if (compiledAppleScript == nil)
{
NSDictionary * errorDict = nil;
NSAppleScript * script = [[[NSAppleScript alloc] initWithSource:embeddedAppleScript] autorelease];
if (script == nil)
{
return [self _errorWithMessage:@"There's a problem with the AppleScript code."];
}
if (![script compileAndReturnError:&errorDict])
{
return [self _errorWithDict:errorDict];
}
[self setCompiledAppleScript:script];
}
// Try to execute the script.
return [self _performAppleScript:compiledAppleScript];
}
@end