/
RunningApplications.m
540 lines (509 loc) · 28 KB
/
RunningApplications.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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
//
// RunningApplications.m
// Slate
//
// Created by Jigish Patel on 3/22/12.
// Copyright 2012 Jigish Patel. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses
#import "RunningApplications.h"
#import "SlateLogger.h"
#import "AccessibilityWrapper.h"
#import "Constants.h"
#import "JSController.h"
#import "JSWindowWrapper.h"
#import "JSApplicationWrapper.h"
#import "SlateConfig.h"
@implementation RunningApplications
@synthesize apps, appNameToApp, windows, appToWindows, titleToWindow, unusedWindowNumbers, nextWindowNumber, pidToObserver;
static RunningApplications *_instance = nil;
+ (RunningApplications *)getInstance {
@synchronized([RunningApplications class]) {
if (!_instance)
_instance = [[[RunningApplications class] alloc] init];
return _instance;
}
}
+ (BOOL)isAppSelectable:(NSRunningApplication *)app {
return [app activationPolicy] == NSApplicationActivationPolicyRegular;
}
static NSDictionary *eventNameDict = nil;
static NSString *prettyifyEventName(NSString *event) {
if (eventNameDict == nil) {
eventNameDict = [NSDictionary dictionaryWithObjectsAndKeys:@"windowClosed", [NSString stringWithFormat:@"%@", kAXUIElementDestroyedNotification],
@"windowMoved", [NSString stringWithFormat:@"%@", kAXMovedNotification],
@"windowResized", [NSString stringWithFormat:@"%@", kAXResizedNotification],
@"windowOpened", [NSString stringWithFormat:@"%@", kAXWindowCreatedNotification],
@"windowFocused", [NSString stringWithFormat:@"%@", kAXFocusedWindowChangedNotification],
@"windowTitleChanged", [NSString stringWithFormat:@"%@", kAXTitleChangedNotification],
@"appClosed", NSWorkspaceDidTerminateApplicationNotification,
@"appOpened", NSWorkspaceDidLaunchApplicationNotification,
@"appHidden", NSWorkspaceDidHideApplicationNotification,
@"appUnhidden", NSWorkspaceDidUnhideApplicationNotification,
@"appActivated", NSWorkspaceDidActivateApplicationNotification,
@"appDeactivated", NSWorkspaceDidDeactivateApplicationNotification, nil];
}
return [eventNameDict objectForKey:event];
}
static void runWindowJSCallbacks(AXUIElementRef element, CFStringRef notification) {
// Run any js callbacks
AccessibilityWrapper *openedWindow = [[AccessibilityWrapper alloc] initWithApp:[AccessibilityWrapper applicationForElement:element] window:element];
NSString *eventName = prettyifyEventName([NSString stringWithFormat:@"%@", notification]);
[[JSController getInstance] runCallbacks:eventName
payload:[[JSWindowWrapper alloc] initWithAccessibilityWrapper:openedWindow screenWrapper:[[ScreenWrapper alloc] init]]];
}
static void windowChanged(AXObserverRef observer, AXUIElementRef element, CFStringRef notification, void *refcon) {
RunningApplications *ref = (__bridge RunningApplications *)refcon;
SlateLogger(@">> WINDOW CHANGED, %@ <<", notification);
if (CFStringCompare(notification, kAXUIElementDestroyedNotification, 0) == kCFCompareEqualTo) {
SlateLogger(@">> WINDOW DESTROYED <<");
AXObserverRemoveNotification(observer, element, kAXUIElementDestroyedNotification);
AXObserverRemoveNotification(observer, element, kAXMovedNotification);
AXObserverRemoveNotification(observer, element, kAXResizedNotification);
[ref pruneWindows];
}
NSString *eventName = prettyifyEventName([NSString stringWithFormat:@"%@", notification]);
[[JSController getInstance] runCallbacks:eventName
payload:[[JSApplicationWrapper alloc] initWithRunningApplication:[NSRunningApplication runningApplicationWithProcessIdentifier:[AccessibilityWrapper processIdentifierOfUIElement:element]] screenWrapper:[[ScreenWrapper alloc] init]]];
}
static void registerForWindowDeath(AXUIElementRef element, RunningApplications *ref) {
// register for death event
AXError err;
AXObserverRef observer;
err = AXObserverCreate([AccessibilityWrapper processIdentifierOfUIElement:element], windowChanged, &observer);
err = AXObserverAddNotification(observer, element, kAXUIElementDestroyedNotification, (__bridge void *)ref);
if (err != kAXErrorSuccess) {
AXObserverRemoveNotification(observer, element, kAXUIElementDestroyedNotification);
return;
}
if ([[SlateConfig getInstance] getBoolConfig:JS_RECEIVE_MOVE_EVENT]) {
err = AXObserverAddNotification(observer, element, kAXMovedNotification, (__bridge void *)ref);
if (err != kAXErrorSuccess) {
AXObserverRemoveNotification(observer, element, kAXMovedNotification);
return;
}
}
if ([[SlateConfig getInstance] getBoolConfig:JS_RECEIVE_RESIZE_EVENT]) {
err = AXObserverAddNotification(observer, element, kAXResizedNotification, (__bridge void *)ref);
if (err != kAXErrorSuccess) {
AXObserverRemoveNotification(observer, element, kAXResizedNotification);
return;
}
}
CFRunLoopAddSource ([[NSRunLoop currentRunLoop] getCFRunLoop], AXObserverGetRunLoopSource(observer), kCFRunLoopDefaultMode);
}
// WINDOW INFO:
// 0 = title
// 1 = NSRunningApplication
// 2 = window number
static void windowCreated(pid_t currPID, AXUIElementRef element, RunningApplications *ref) {
SlateLogger(@">> WINDOW CREATED <<");
[ref pruneWindows];
NSString *title = [AccessibilityWrapper getTitle:element];
if (title == nil || [EMPTY isEqualToString:title]) return; // skip empty title windows because they are invisible
NSMutableArray *windowInfo = [NSMutableArray array];
[windowInfo addObject:title];
[windowInfo addObject:[NSRunningApplication runningApplicationWithProcessIdentifier:currPID]];
if ([[ref unusedWindowNumbers] count] > 0) {
[windowInfo addObject:[[ref unusedWindowNumbers] objectAtIndex:0]];
[[ref unusedWindowNumbers] removeObjectAtIndex:0];
} else {
[windowInfo addObject:[NSNumber numberWithInteger:[ref nextWindowNumber]]];
[ref setNextWindowNumber:[ref nextWindowNumber]+1];
}
[[ref windows] insertObject:windowInfo atIndex:0];
if ([[ref titleToWindow] objectForKey:title]) {
[[[ref titleToWindow] objectForKey:title] addObject:windowInfo];
} else {
[[ref titleToWindow] setObject:[NSMutableArray arrayWithObject:windowInfo] forKey:title];
}
[[[ref appToWindows] objectForKey:[NSNumber numberWithInteger:currPID]] addObject:windowInfo];
registerForWindowDeath(element, ref);
}
+ (NSRunningApplication *)focusedApp {
NSWorkspace *sharedWorkspace = [NSWorkspace sharedWorkspace];
if ([sharedWorkspace respondsToSelector:@selector(frontmostApplication)]) {
return [sharedWorkspace frontmostApplication];
} else {
AccessibilityWrapper *aw = [[AccessibilityWrapper alloc] init];
return [NSRunningApplication runningApplicationWithProcessIdentifier:[aw processIdentifier]];
}
}
static void windowCallback(AXObserverRef observer, AXUIElementRef element, CFStringRef notification, void *refcon) {
SlateLogger(@">>> %@ for %@", notification, [AccessibilityWrapper getRole:element]);
if (![AccessibilityWrapper isWindow:element]) return;
RunningApplications *ref = (__bridge RunningApplications *)refcon;
pid_t currPID = [AccessibilityWrapper processIdentifierOfUIElement:element];
// Title Changed, update windows
if (CFStringCompare(notification, kAXTitleChangedNotification, 0) == kCFCompareEqualTo) {
SlateLogger(@">>> TITLE CHANGED TO %@", [AccessibilityWrapper getTitle:element]);
NSNumber *appPID = [NSNumber numberWithInteger:[AccessibilityWrapper processIdentifierOfUIElement:element]];
NSMutableArray *oldWindowsInApp = [[[ref appToWindows] objectForKey:appPID] mutableCopy];
CFArrayRef windowsArr = [AccessibilityWrapper windowsInApp:AXUIElementCreateApplication([appPID intValue])];
// Remove all windows if app has no windows
if (!windowsArr || CFArrayGetCount(windowsArr) == 0) return;
if (oldWindowsInApp == nil || [oldWindowsInApp count] == 0) {
windowCreated(currPID, element, ref);
runWindowJSCallbacks(element, notification);
return;
}
// set up title counts
NSMutableDictionary *tmpTitleToCount = [NSMutableDictionary dictionary];
for (NSMutableArray *windowInfo in oldWindowsInApp) {
NSString *title = [windowInfo objectAtIndex:0];
if ([tmpTitleToCount objectForKey:title]) {
[tmpTitleToCount setObject:[NSNumber numberWithInteger:([[tmpTitleToCount objectForKey:title] integerValue]+1)] forKey:title];
} else {
[tmpTitleToCount setObject:[NSNumber numberWithInteger:1] forKey:title];
}
}
// figure out which title is new
NSString *newTitle = nil;
for (NSInteger i = 0; i < CFArrayGetCount(windowsArr); i++) {
AXUIElementRef window = CFArrayGetValueAtIndex(windowsArr, i);
NSString *currTitle = [AccessibilityWrapper getTitle:window];
NSNumber *currCount = [tmpTitleToCount objectForKey:currTitle];
if (currCount == nil || [currCount integerValue] == 0) {
newTitle = currTitle;
} else {
[tmpTitleToCount setObject:[NSNumber numberWithInteger:([currCount integerValue]-1)] forKey:currTitle];
}
}
// figure out which title is old
NSString *oldTitle = nil;
for (NSString *currTitle in [tmpTitleToCount allKeys]) {
NSNumber *currCount = [tmpTitleToCount objectForKey:currTitle];
if (currCount != nil && [currCount integerValue] > 0) {
oldTitle = currTitle;
break;
}
}
// out with the old and in with the new
if (oldTitle != nil && newTitle != nil) {
for (NSMutableArray *windowInfo in oldWindowsInApp) {
if ([[windowInfo objectAtIndex:0] isEqualToString:oldTitle]) {
[windowInfo removeObjectAtIndex:0];
[windowInfo insertObject:[AccessibilityWrapper getTitle:element] atIndex:0];
NSMutableArray *windowsForTitle = [[ref titleToWindow] objectForKey:oldTitle];
if (!windowsForTitle || [windowsForTitle count] == 0) continue;
if ([windowsForTitle count] == 1) {
[[ref titleToWindow] removeObjectForKey:oldTitle];
} else {
[windowsForTitle removeObject:windowInfo];
}
windowsForTitle = [[ref titleToWindow] objectForKey:[windowInfo objectAtIndex:0]];
if (!windowsForTitle) {
[[ref titleToWindow] setObject:[NSMutableArray arrayWithObject:windowInfo] forKey:[windowInfo objectAtIndex:0]];
} else {
[windowsForTitle insertObject:windowInfo atIndex:0];
[[ref titleToWindow] setObject:windowsForTitle forKey:[windowInfo objectAtIndex:0]];
}
[ref pruneWindows];
runWindowJSCallbacks(element, notification);
return;
}
}
}
[ref pruneWindows];
runWindowJSCallbacks(element, notification);
return;
}
// Focus Changed, update windows
if (CFStringCompare(notification, kAXFocusedWindowChangedNotification, 0) == kCFCompareEqualTo) {
[ref pruneWindows];
runWindowJSCallbacks(element, notification);
return;
}
// Window created, add to windows
windowCreated(currPID, element, ref);
runWindowJSCallbacks(element, notification);
SlateLogger(@">>> END %@ for %@", notification, [AccessibilityWrapper getRole:element]);
}
- (id)init {
self = [super init];
if (self) {
unusedWindowNumbers = [NSMutableArray array];
nextWindowNumber = 0;
apps = [NSMutableArray array];
appNameToApp = [NSMutableDictionary dictionary];
windows = [NSMutableArray array];
appToWindows = [NSMutableDictionary dictionary];
pidToObserver = [NSMutableDictionary dictionary];
titleToWindow = [NSMutableDictionary dictionary];
SlateLogger(@"------------------ Checking Running Applications ------------------");
NSArray *appsArr = [[NSWorkspace sharedWorkspace] runningApplications];
NSRunningApplication *currentApp = [NSRunningApplication currentApplication];
for (NSRunningApplication *app in appsArr) {
if ([RunningApplications isAppSelectable:app]) {
SlateLogger(@" Selectable: %@", [app localizedName]);
[apps addObject:app];
[appNameToApp setObject:app forKey:[app localizedName]];
SlateLogger(@" I see application '%@'", [app localizedName]);
// check for windows
NSNumber *appPID = [NSNumber numberWithInteger:[app processIdentifier]];
[appToWindows setObject:[NSMutableArray array] forKey:appPID];
AXUIElementRef appRef = AXUIElementCreateApplication([app processIdentifier]);
CFArrayRef windowsArr = [AccessibilityWrapper windowsInApp:appRef];
if (windowsArr && CFArrayGetCount(windowsArr) > 0) {
SlateLogger(@" Has Windows: %@", [app localizedName]);
for (NSInteger i = 0; i < CFArrayGetCount(windowsArr); i++) {
NSMutableArray *windowInfo = [NSMutableArray array];
AXUIElementRef window = CFArrayGetValueAtIndex(windowsArr, i);
NSString *title = [AccessibilityWrapper getTitle:window];
if (title == nil || [EMPTY isEqualToString:title]) continue; // skip empty title windows because they are invisible
SlateLogger(@" Title: %@", title);
[windowInfo addObject:title];
[windowInfo addObject:app];
[windowInfo addObject:[NSNumber numberWithInteger:nextWindowNumber]];
if ([self isCurrentApplication:app] && [AccessibilityWrapper isMainWindow:window]) {
[windows insertObject:windowInfo atIndex:0];
[[appToWindows objectForKey:appPID] insertObject:windowInfo atIndex:0];
} else if ([AccessibilityWrapper isMainWindow:window]) {
[windows addObject:windowInfo];
[[appToWindows objectForKey:appPID] insertObject:windowInfo atIndex:0];
} else {
[windows addObject:windowInfo];
[[appToWindows objectForKey:appPID] addObject:windowInfo];
}
NSMutableArray *windowsForTitle = [titleToWindow objectForKey:title];
if (!windowsForTitle) {
[titleToWindow setObject:[NSMutableArray arrayWithObject:windowInfo] forKey:title];
} else {
[windowsForTitle addObject:windowInfo];
[titleToWindow setObject:windowsForTitle forKey:title];
}
registerForWindowDeath(window, self);
nextWindowNumber++;
}
}
if ([self isCurrentApplication:app]) {
currentApp = app;
}
AXError err;
AXUIElementRef sendingApp = AXUIElementCreateApplication([app processIdentifier]);
AXObserverRef observer;
err = AXObserverCreate([app processIdentifier], windowCallback, &observer);
err = AXObserverAddNotification(observer, sendingApp, kAXWindowCreatedNotification, (__bridge void *)self);
err = AXObserverAddNotification(observer, sendingApp, kAXFocusedWindowChangedNotification, (__bridge void *)self);
err = AXObserverAddNotification(observer, sendingApp, kAXTitleChangedNotification, (__bridge void *)self);
if (err != kAXErrorSuccess) {
AXObserverRemoveNotification(observer, sendingApp, kAXWindowCreatedNotification);
AXObserverRemoveNotification(observer, sendingApp, kAXFocusedWindowChangedNotification);
AXObserverRemoveNotification(observer, sendingApp, kAXTitleChangedNotification);
} else {
CFRunLoopAddSource ([[NSRunLoop currentRunLoop] getCFRunLoop], AXObserverGetRunLoopSource(observer), kCFRunLoopDefaultMode);
[pidToObserver setObject:[NSValue valueWithPointer:observer] forKey:[NSNumber numberWithInteger:[app processIdentifier]]];
}
}
}
SlateLogger(@"CURRENT APP = '%@'", [currentApp localizedName]);
[self bringAppToFront:currentApp];
SlateLogger(@"------------------ Done Checking Running Applications ------------------");
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(applicationKilled:) name:NSWorkspaceDidTerminateApplicationNotification object:nil];
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(applicationLaunched:) name:NSWorkspaceDidLaunchApplicationNotification object:nil];
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(applicationDeactivated:) name:NSWorkspaceDidHideApplicationNotification object:nil];
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(applicationActivated:) name:NSWorkspaceDidUnhideApplicationNotification object:nil];
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(applicationDeactivated:) name:NSWorkspaceDidDeactivateApplicationNotification object:nil];
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(applicationActivated:) name:NSWorkspaceDidActivateApplicationNotification object:nil];
}
return self;
}
- (NSRunningApplication *)currentApplication {
// ownsMenuBar is 10.7+ only
if ([[NSRunningApplication currentApplication] respondsToSelector:@selector(ownsMenuBar)]) {
NSArray *appsArr = [[NSWorkspace sharedWorkspace] runningApplications];
for (NSRunningApplication *app in appsArr) {
if ([RunningApplications isAppSelectable:app]) {
if ([app ownsMenuBar]) return app;
}
}
}
return [NSRunningApplication currentApplication];
}
- (BOOL)isCurrentApplication:(NSRunningApplication *)app {
// ownsMenuBar is 10.7+ only
if ([[NSRunningApplication currentApplication] respondsToSelector:@selector(ownsMenuBar)]) {
return [app ownsMenuBar];
}
return app == [NSRunningApplication currentApplication];
}
- (void)pruneWindows {
NSArray *windowsCopy = [windows copy];
for (NSArray *windowInfo in windowsCopy) {
if (![apps containsObject:[windowInfo objectAtIndex:1]]) {
[self removeWindow:windowInfo];
SlateLogger(@" PRUNE Because app died");
}
}
for (NSRunningApplication *app in apps) {
NSNumber *appPID = [NSNumber numberWithInteger:[app processIdentifier]];
NSMutableArray *oldWindowsInApp = [[appToWindows objectForKey:appPID] mutableCopy];
CFArrayRef windowsArr = [AccessibilityWrapper windowsInRunningApp:app];
// Remove all windows if app has no windows
if (!windowsArr || CFArrayGetCount(windowsArr) == 0) {
NSArray *windowsToRemove = [[appToWindows objectForKey:appPID] copy];
for (NSArray *windowInfo in windowsToRemove) {
[self removeWindow:windowInfo];
SlateLogger(@" PRUNE Because app has no windows");
}
continue;
}
// Remove windows that are no longer open. No need to add windows that we havn't seen because technically our callback should catch it.
for (NSArray *windowInfo in oldWindowsInApp) {
BOOL found = NO;
for (NSInteger i = 0; i < CFArrayGetCount(windowsArr); i++) {
AXUIElementRef window = CFArrayGetValueAtIndex(windowsArr, i);
if ([[windowInfo objectAtIndex:0] isEqualToString:[AccessibilityWrapper getTitle:window]]) {
found = YES;
}
}
if (!found) {
[self removeWindow:windowInfo];
SlateLogger(@" PRUNE Because title mismatch");
}
}
}
}
- (void)removeWindow:(NSArray *)windowInfo {
[unusedWindowNumbers addObject:[windowInfo objectAtIndex:2]];
[windows removeObject:windowInfo];
NSNumber *appPID = [NSNumber numberWithInteger:[[windowInfo objectAtIndex:1] processIdentifier]];
if ([appToWindows objectForKey:appPID] != nil) {
[[appToWindows objectForKey:appPID] removeObject:windowInfo];
}
NSMutableArray *windowsForTitle = [titleToWindow objectForKey:[windowInfo objectAtIndex:0]];
if (!windowsForTitle || [windowsForTitle count] <= 1) {
[titleToWindow removeObjectForKey:[windowInfo objectAtIndex:0]];
} else {
[windowsForTitle removeObject:windowInfo];
[titleToWindow setObject:windowsForTitle forKey:[windowInfo objectAtIndex:0]];
}
}
/*- (void)notificationRecieved:(id)notification {
SlateLogger(@"NOTE RECIEVED: %@", [notification name]);
}*/
- (void)applicationActivated:(id)notification {
SlateLogger(@"Activated: %@", [notification name]);
NSRunningApplication *activatedApp = [[notification userInfo] objectForKey:NSWorkspaceApplicationKey];
if ([[activatedApp localizedName] isEqualToString:@"Slate"]) return;
[self bringAppToFront:activatedApp];
[self pruneWindows];
NSString *eventName = prettyifyEventName([notification name]);
[[JSController getInstance] runCallbacks:eventName
payload:[[JSApplicationWrapper alloc] initWithRunningApplication:activatedApp screenWrapper:[[ScreenWrapper alloc] init]]];
}
- (void)applicationDeactivated:(id)notification {
SlateLogger(@"Deactivated: %@", [notification name]);
NSRunningApplication *deactivatedApp = [[notification userInfo] objectForKey:NSWorkspaceApplicationKey];
NSString *eventName = prettyifyEventName([notification name]);
[[JSController getInstance] runCallbacks:eventName
payload:[[JSApplicationWrapper alloc] initWithRunningApplication:deactivatedApp screenWrapper:[[ScreenWrapper alloc] init]]];
}
- (void)applicationLaunched:(id)notification {
SlateLogger(@"Launched: %@", [notification name]);
NSRunningApplication *launchedApp = [[notification userInfo] objectForKey:NSWorkspaceApplicationKey];
if ([[launchedApp localizedName] isEqualToString:@"Slate"]) return;
NSNumber *appPID = [NSNumber numberWithInteger:[launchedApp processIdentifier]];
[appToWindows setObject:[NSMutableArray array] forKey:appPID];
AXError err;
AXUIElementRef sendingApp = AXUIElementCreateApplication([launchedApp processIdentifier]);
AXObserverRef observer;
err = AXObserverCreate([launchedApp processIdentifier], windowCallback, &observer);
if (err != kAXErrorSuccess) return;
err = AXObserverAddNotification(observer, sendingApp, kAXWindowCreatedNotification, (__bridge void *)self);
err = AXObserverAddNotification(observer, sendingApp, kAXFocusedWindowChangedNotification, (__bridge void *)self);
err = AXObserverAddNotification(observer, sendingApp, kAXTitleChangedNotification, (__bridge void *)self);
if (err != kAXErrorSuccess) {
AXObserverRemoveNotification(observer, AXUIElementCreateApplication([launchedApp processIdentifier]), kAXWindowCreatedNotification);
AXObserverRemoveNotification(observer, AXUIElementCreateApplication([launchedApp processIdentifier]), kAXFocusedWindowChangedNotification);
AXObserverRemoveNotification(observer, AXUIElementCreateApplication([launchedApp processIdentifier]), kAXTitleChangedNotification);
return;
}
CFRunLoopAddSource ([[NSRunLoop currentRunLoop] getCFRunLoop], AXObserverGetRunLoopSource(observer), kCFRunLoopDefaultMode);
[pidToObserver setObject:[NSValue valueWithPointer:observer] forKey:[NSNumber numberWithInteger:[launchedApp processIdentifier]]];
// add already created windows
CFArrayRef windowsArr = [AccessibilityWrapper windowsInApp:AXUIElementCreateApplication([launchedApp processIdentifier])];
if (windowsArr != NULL) {
for (NSInteger i = 0; i < CFArrayGetCount(windowsArr); i++) {
AXUIElementRef element = CFArrayGetValueAtIndex(windowsArr, i);
NSString *title = [AccessibilityWrapper getTitle:element];
if (title == nil || [EMPTY isEqualToString:title]) continue; // skip empty title windows because they are invisible
NSMutableArray *windowInfo = [NSMutableArray array];
[windowInfo addObject:title];
[windowInfo addObject:[NSRunningApplication runningApplicationWithProcessIdentifier:[launchedApp processIdentifier]]];
if ([[self unusedWindowNumbers] count] > 0) {
[windowInfo addObject:[[self unusedWindowNumbers] objectAtIndex:0]];
[[self unusedWindowNumbers] removeObjectAtIndex:0];
} else {
[windowInfo addObject:[NSNumber numberWithInteger:[self nextWindowNumber]]];
[self setNextWindowNumber:[self nextWindowNumber]+1];
}
[[self windows] insertObject:windowInfo atIndex:0];
NSMutableArray *windowsForTitle = [[self titleToWindow] objectForKey:title];
if (!windowsForTitle) {
[[self titleToWindow] setObject:[NSMutableArray arrayWithObject:windowInfo] forKey:title];
} else {
[windowsForTitle addObject:windowInfo];
[[self titleToWindow] setObject:windowsForTitle forKey:title];
}
[[[self appToWindows] objectForKey:[NSNumber numberWithInteger:[launchedApp processIdentifier]]] addObject:windowInfo];
}
}
[self bringAppToFront:launchedApp];
[self pruneWindows];
NSString *eventName = prettyifyEventName([notification name]);
[[JSController getInstance] runCallbacks:eventName
payload:[[JSApplicationWrapper alloc] initWithRunningApplication:launchedApp screenWrapper:[[ScreenWrapper alloc] init]]];
}
- (void)applicationKilled:(id)notification {
SlateLogger(@"Killed: %@", [notification name]);
NSRunningApplication *app = [[notification userInfo] objectForKey:NSWorkspaceApplicationKey];
[apps removeObject:app];
[appNameToApp removeObjectForKey:[app localizedName]];
NSNumber *appPID = [NSNumber numberWithInteger:[app processIdentifier]];
[appToWindows removeObjectForKey:appPID];
AXObserverRemoveNotification([[pidToObserver objectForKey:[NSNumber numberWithInteger:[app processIdentifier]]] pointerValue], AXUIElementCreateApplication([app processIdentifier]), kAXWindowCreatedNotification);
AXObserverRemoveNotification([[pidToObserver objectForKey:[NSNumber numberWithInteger:[app processIdentifier]]] pointerValue], AXUIElementCreateApplication([app processIdentifier]), kAXFocusedWindowChangedNotification);
AXObserverRemoveNotification([[pidToObserver objectForKey:[NSNumber numberWithInteger:[app processIdentifier]]] pointerValue], AXUIElementCreateApplication([app processIdentifier]), kAXTitleChangedNotification);
[pidToObserver removeObjectForKey:[NSNumber numberWithInteger:[app processIdentifier]]];
[self pruneWindows];
[self bringAppToFront:[self currentApplication]];
NSString *eventName = prettyifyEventName([notification name]);
[[JSController getInstance] runCallbacks:eventName
payload:[[JSApplicationWrapper alloc] initWithRunningApplication:app screenWrapper:[[ScreenWrapper alloc] init]]];
}
- (void)bringAppToFront:(NSRunningApplication *)app {
if (![RunningApplications isAppSelectable:app]) return;
[apps removeObject:app];
[apps insertObject:app atIndex:0];
#ifdef DEBUG
SlateLogger(@" New App Order:");
for (NSRunningApplication *app in apps) {
SlateLogger(@" %@", [app localizedName]);
}
#endif
}
- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(__unsafe_unretained id *)stackbuf count:(NSUInteger)len {
return [apps countByEnumeratingWithState:state objects:stackbuf count:len];
}
- (NSArray *)windowIdsForTitle:(NSString *)title {
NSArray *windowsForTitle = [titleToWindow objectForKey:title];
if (windowsForTitle == nil || [windowsForTitle count] == 0) return nil;
NSMutableArray *windowIdsForTitle = [NSMutableArray array];
for(NSArray *windowInfo in windowsForTitle) {
[windowIdsForTitle addObject:[windowInfo objectAtIndex:2]];
}
return windowIdsForTitle;
}
@end