forked from millenomi/afloat
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Afloat.m
562 lines (426 loc) · 17.9 KB
/
Afloat.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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
/*
Copyright (c) 2008, Emanuele Vulcano
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "Afloat.h"
#import <math.h>
#import "JRSwizzle.h"
#import "AfloatStorage.h"
#import "AfloatPanelController.h"
#import "AfloatBadgeController.h"
#import "Afloat_AfloatNagging.h"
#import "Afloat_AfloatScripting.h"
#define kAfloatTranslucentAlphaValue (0.7f)
#define kAfloatMinimumAlphaValue (0.3f)
#define kAfloatOverlayAlphaValue (0.4f)
#define kAfloatLastAlphaValueKey @"AfloatLastAlphaValue"
#define kAfloatTrackingAreaKey @"AfloatTrackingArea"
#define kAfloatTrackedViewKey @"AfloatTrackedView"
#define kAfloatLastSpacesSettingKey @"AfloatLastSpacesSetting"
#define kAfloatAlphaValueAnimationEnabledKey @"AfloatAlphaValueAnimationEnabled"
#define kAfloatIsOverlayKey @"AfloatIsOverlay"
///////////////////////////////////////
@interface NSApplication (Afloat)
- (void) afloat_sendEvent:(NSEvent*) event;
@end
///////////////////////////////////////
@interface Afloat ()
- (NSUInteger) indexForInstallingInMenu:(NSMenu*) m;
- (void) install;
- (void) beginTrackingWindow:(NSWindow*) w;
- (void) endTrackingWindow:(NSWindow*) w;
- (BOOL) isWindowIgnoredByAfloat:(NSWindow*) w;
- (NSWindow*) highestWindowInHierarchyFor:(NSWindow*) w;
@end
@implementation Afloat
+ (id) sharedInstance {
static id myself = nil;
if (!myself) myself = [self new];
return myself;
}
+ (void) load {
static BOOL alreadyLoaded = NO;
if (alreadyLoaded) return; alreadyLoaded = YES;
[[self sharedInstance] install];
}
- (id) init {
self = [super init];
if (self != nil) {
AfloatStorage* shared = [AfloatStorage sharedStorage];
shared.delegate = self;
}
return self;
}
- (void) storage:(AfloatStorage*) s willRemoveMutableDictionary:(NSMutableDictionary*) d forWindow:(NSWindow*) w {
[self endTrackingWindow:w];
}
- (void) install {
// Set up menu items ---------------------------------------
NSMenu* menu = [NSApp windowsMenu];
if (!menu) {
L0Log(@"%@ found no Window menu in NSApp %@", self, NSApp);
return;
}
NSUInteger index = [self indexForInstallingInMenu:menu];
[NSBundle loadNibNamed:@"Afloat" owner:self];
NSImage* badge = [[NSImage alloc] initWithContentsOfFile:
[[self bundle] pathForImageResource:@"AfloatMenuBadge"]];
NSArray* a = [NSArray arrayWithArray:[_menuWithItems itemArray]];
if (index < [menu numberOfItems] && ![[menu itemAtIndex:index] isSeparatorItem])
[menu insertItem:[NSMenuItem separatorItem] atIndex:index];
for (NSMenuItem* item in a) {
[_menuWithItems removeItem:item];
if (![item isSeparatorItem])
[item setImage:badge];
[menu insertItem:item atIndex:index];
index++;
}
if (index < [menu numberOfItems] && ![[menu itemAtIndex:index] isSeparatorItem])
[menu insertItem:[NSMenuItem separatorItem] atIndex:index];
[badge release];
[_menuWithItems release]; _menuWithItems = nil;
// Set up swizzling sendEvents: in NSApplication --------------
NSError* err = nil;
BOOL result = [NSApplication jr_swizzleMethod:@selector(sendEvent:) withMethod:@selector(afloat_sendEvent:) error:&err];
if (!result) // we want this to be visible to end users, too :)
NSLog(@"<Afloat> Could not install events filter (error: %@). Some features may not work.", err);
// Set up window did become main/did resign main notification
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidBecomeMain:) name:NSWindowDidBecomeMainNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidResignMain:) name:NSWindowDidResignMainNotification object:nil];
// Nag, nag, nag, nag, nag, nag, nag, nag...
// delayed -- PS already slows down app launch enough.
//[self checkForNagOnInstall];
[self performSelector:@selector(checkForNagOnInstall) withObject:nil afterDelay:7.0];
// Scripting support.
[self installScriptingSupport];
}
- (NSUInteger) indexForInstallingInMenu:(NSMenu*) m {
NSUInteger i = 0, lastSeparator = -1;
for (NSMenuItem* item in [m itemArray]) {
if ([item isSeparatorItem])
lastSeparator = i;
else if ([item action] == @selector(arrangeInFront:))
return i + 1;
i++;
}
if (lastSeparator != -1)
return lastSeparator + 1;
else
return 0;
}
- (NSBundle*) bundle {
return [NSBundle bundleForClass:[self class]];
}
- (IBAction) toggleAlwaysOnTop:(id) sender {
NSWindow* c = [self currentWindow];
if (c)
[self setKeptAfloat:![self isWindowKeptAfloat:c] forWindow:c showBadgeAnimation:YES];
}
- (BOOL) validateMenuItem:(NSMenuItem*) item {
if ([item action] == @selector(toggleAlwaysOnTop:)) {
NSWindow* c = [self currentWindow];
if (!c)
[item setState:NSOffState];
else
[item setState:[self isWindowKeptAfloat:c]? NSOnState : NSOffState];
return c != nil;
} else if ([item action] == @selector(showWindowFileInFinder:))
return [[self currentWindow] representedURL]? [[[self currentWindow] representedURL] isFileURL] : NO;
return YES;
}
- (BOOL) isWindowKeptAfloat:(NSWindow*) w {
return [w level] != NSNormalWindowLevel;
}
- (void) setKeptAfloat:(BOOL) afloat forWindow:(NSWindow*) c showBadgeAnimation:(BOOL) animated {
L0Log(@"window = %@, will be afloat = %d, was afloat = %d", c, afloat, [self isWindowKeptAfloat:c]);
BOOL wasKeptElsewhere = [self isWindowKeptAfloat:c] || [self isWindowKeptPinnedToDesktop:c];
if (afloat) {
[c setLevel:NSFloatingWindowLevel];
if (!wasKeptElsewhere && animated) {
L0LogS(@"Starting begin keeping afloat animation...");
[[AfloatBadgeController badgeControllerForWindow:c] animateWithBadgeType:AfloatBadgeDidBeginKeepingAfloat];
}
} else if (!afloat) {
[c setLevel:NSNormalWindowLevel];
if (wasKeptElsewhere && animated) {
L0LogS(@"Starting end keeping afloat animation...");
[[AfloatBadgeController badgeControllerForWindow:c] animateWithBadgeType:AfloatBadgeDidEndKeepingAfloat];
}
}
if (!afloat && [self isWindowOverlay:c] && !_settingOverlay)
[self setOverlay:NO forWindow:c animated:animated showBadgeAnimation:NO];
}
- (void) setOnAllSpaces:(BOOL) spaces forWindow:(NSWindow*) c {
if ([c collectionBehavior] != NSWindowCollectionBehaviorCanJoinAllSpaces && spaces) {
[AfloatStorage setSharedValue:[NSNumber numberWithUnsignedInteger:[c collectionBehavior]]
window:c key:kAfloatLastSpacesSettingKey];
[c setCollectionBehavior:NSWindowCollectionBehaviorCanJoinAllSpaces];
} else {
NSNumber* n = [AfloatStorage sharedValueForWindow:c key:kAfloatLastSpacesSettingKey];
NSUInteger setting = NSWindowCollectionBehaviorDefault;
if (c)
setting = [n unsignedIntegerValue];
[c setCollectionBehavior:setting];
[AfloatStorage removeSharedValueForWindow:c key:kAfloatLastSpacesSettingKey];
}
}
- (BOOL) isWindowOnAllSpaces:(NSWindow*) w {
return [w collectionBehavior] == NSWindowCollectionBehaviorCanJoinAllSpaces;
}
- (NSWindow*) highestWindowInHierarchyFor:(NSWindow*) w;
{
while ([w parentWindow])
w = [w parentWindow];
return w;
}
- (NSWindow*) currentWindow {
NSWindow* w;
w = [self highestWindowInHierarchyFor:[NSApp keyWindow]];
if (![self isWindowIgnoredByAfloat:w]) return w;
w = [self highestWindowInHierarchyFor:[NSApp mainWindow]];
if (![self isWindowIgnoredByAfloat:w]) return w;
for (NSWindow* window in [NSApp orderedWindows]) {
w = [self highestWindowInHierarchyFor:window];
if (![self isWindowIgnoredByAfloat:w])
return w;
}
return nil;
}
- (BOOL) isWindowIgnoredByAfloat:(NSWindow*) w {
return [w isKindOfClass:[NSPanel class]] || ![w isVisible];
}
- (IBAction) makeTranslucent:(id) sender {
NSWindow* c = [self currentWindow];
if (c)
[self setAlphaValue:kAfloatTranslucentAlphaValue forWindow:[self currentWindow] animated:YES];
}
- (IBAction) makeOpaque:(id) sender {
NSWindow* c = [self currentWindow];
if (c)
[self setAlphaValue:1.0 forWindow:[self currentWindow] animated:YES];
}
- (IBAction) makeMoreTransparent:(id) sender {
NSWindow* c = [self currentWindow];
if (c)
[self setAlphaValueByDelta:-0.1 forWindow:[self currentWindow] animate:NO];
}
- (IBAction) makeLessTransparent:(id) sender {
NSWindow* c = [self currentWindow];
if (c)
[self setAlphaValueByDelta:0.1 forWindow:[self currentWindow] animate:NO];
}
- (CGFloat) currentAlphaValueForWindow:(NSWindow*) window {
id alphaValue = [AfloatStorage sharedValueForWindow:window key:kAfloatLastAlphaValueKey];
return (alphaValue)? [alphaValue floatValue] : [window alphaValue];
}
- (void) setAlphaValueByDelta:(CGFloat) delta forWindow:(NSWindow*) window animate:(BOOL) animate {
if (!window) return;
float a = [self currentAlphaValueForWindow:window];
[self setAlphaValue:a + delta forWindow:window animated:animate];
}
- (void) setAlphaValue:(CGFloat) f forWindow:(NSWindow*) window animated:(BOOL) animate {
if (!window) return;
if (f > 1.0)
f = 1.0;
else if (f < kAfloatMinimumAlphaValue)
f = kAfloatMinimumAlphaValue;
[AfloatStorage setSharedValue:[NSNumber numberWithFloat:f] window:window key:kAfloatLastAlphaValueKey];
if (f == 1.0)
[self endTrackingWindow:window];
else
[self beginTrackingWindow:window];
if (animate) {
[NSAnimationContext beginGrouping];
[[NSAnimationContext currentContext] setDuration:0.3];
[(NSWindow*)[window animator] setAlphaValue:f];
[NSAnimationContext endGrouping];
} else
[window setAlphaValue:f];
}
- (void) setAlphaValueAnimatesOnMouseOver:(BOOL) animates forWindow:(NSWindow*) window {
if (animates)
[AfloatStorage setSharedValue:[NSNumber numberWithBool:YES] window:window key:kAfloatAlphaValueAnimationEnabledKey];
else
[AfloatStorage removeSharedValueForWindow:window key:kAfloatAlphaValueAnimationEnabledKey];
}
- (BOOL) alphaValueAnimatesOnMouseOverForWindow:(NSWindow*) window {
return [AfloatStorage sharedValueForWindow:window key:kAfloatAlphaValueAnimationEnabledKey] != nil;
}
- (void) beginTrackingWindow:(NSWindow*) window {
L0Log(@"window = %@", window);
if ([AfloatStorage sharedValueForWindow:window key:kAfloatTrackingAreaKey])
return;
NSView* v = [[window contentView] superview];
NSTrackingArea* tracker = [[NSTrackingArea alloc] initWithRect:[v bounds] options:NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways | NSTrackingInVisibleRect owner:self userInfo:nil];
[v addTrackingArea:tracker];
[AfloatStorage setSharedValue:tracker window:window key:kAfloatTrackingAreaKey];
[AfloatStorage setSharedValue:v window:window key:kAfloatTrackedViewKey];
L0Log(@"tracker = %@ view = %@", tracker, v);
[tracker release];
}
- (void) endTrackingWindow:(NSWindow*) window {
L0Log(@"window = %@", window);
NSTrackingArea* area = [AfloatStorage sharedValueForWindow:window key:kAfloatTrackingAreaKey];
NSView* view = [AfloatStorage sharedValueForWindow:window key:kAfloatTrackedViewKey];
if (view && area)
[view removeTrackingArea:area];
[AfloatStorage removeSharedValueForWindow:window key:kAfloatTrackingAreaKey];
[AfloatStorage removeSharedValueForWindow:window key:kAfloatTrackedViewKey];
}
- (void) mouseEntered:(NSEvent*) e {
L0Log(@"%@", e);
[self animateFadeInForWindow:[e window]];
}
- (void) windowDidBecomeMain:(NSNotification*) n {
[self animateFadeInForWindow:[n object]];
}
- (void) animateFadeInForWindow:(NSWindow*) w {
if (![self alphaValueAnimatesOnMouseOverForWindow:w]) return;
[NSAnimationContext beginGrouping];
[[NSAnimationContext currentContext] setDuration:0.2];
[[w animator] setAlphaValue:1.0];
[NSAnimationContext endGrouping];
}
- (void) mouseExited:(NSEvent*) e {
L0Log(@"%@", e);
[self animateFadeOutForWindow:[e window]];
}
- (void) windowDidResignMain:(NSNotification*) n {
[self animateFadeOutForWindow:[n object]];
}
- (void) animateFadeOutForWindow:(NSWindow*) w {
if (![self alphaValueAnimatesOnMouseOverForWindow:w]) return;
id alphaValue = [AfloatStorage sharedValueForWindow:w key:kAfloatLastAlphaValueKey];
if (!alphaValue) return;
float a = [alphaValue floatValue];
[NSAnimationContext beginGrouping];
[[NSAnimationContext currentContext] setDuration:0.5];
[[w animator] setAlphaValue:a];
[NSAnimationContext endGrouping];
}
- (IBAction) showAdjustEffectsPanel:(id) sender {
NSWindow* w = [self currentWindow];
if (!w) { NSBeep(); return; }
AfloatPanelController* ctl = [AfloatPanelController panelControllerForWindow:w];
[ctl toggleWindow:self];
}
- (void) setOverlay:(BOOL) overlay forWindow:(NSWindow*) w animated:(BOOL) animated showBadgeAnimation:(BOOL) badge {
_settingOverlay = YES;
if (overlay) {
[self setKeptAfloat:YES forWindow:w showBadgeAnimation:badge];
[self setAlphaValue:kAfloatOverlayAlphaValue forWindow:w animated:animated];
[self setAlphaValueAnimatesOnMouseOver:NO forWindow:w];
[w setIgnoresMouseEvents:YES];
[AfloatStorage setSharedValue:[NSNumber numberWithBool:YES] window:w key:kAfloatIsOverlayKey];
} else {
if ([w alphaValue] <= kAfloatOverlayAlphaValue)
[self setAlphaValue:1.0 forWindow:w animated:animated];
// [self setAlphaValueAnimatesOnMouseOver:YES forWindow:w];
[self setKeptAfloat:NO forWindow:w showBadgeAnimation:badge];
[w setIgnoresMouseEvents:NO];
[AfloatStorage removeSharedValueForWindow:w key:kAfloatIsOverlayKey];
}
_settingOverlay = NO;
}
- (BOOL) isWindowOverlay:(NSWindow*) overlay {
return [AfloatStorage sharedValueForWindow:overlay key:kAfloatIsOverlayKey] != nil;
}
- (IBAction) disableAllOverlays:(id) sender {
[self disableAllOverlaysShowingBadgeAnimation:YES];
}
- (void) disableAllOverlaysShowingBadgeAnimation:(BOOL) badge {
for (NSWindow* w in [NSApp orderedWindows]) {
if (![self isWindowIgnoredByAfloat:w])
[self setOverlay:NO forWindow:w animated:YES showBadgeAnimation:badge];
}
}
- (IBAction) showWindowFileInFinder:(id) sender {
NSURL* url = [[self currentWindow] representedURL];
if (!url || ![url isFileURL]) { NSBeep(); return; }
[[NSWorkspace sharedWorkspace] selectFile:[url path] inFileViewerRootedAtPath:@""];
}
- (void) setKeptPinnedToDesktop:(BOOL) pinned forWindow:(NSWindow*) c showBadgeAnimation:(BOOL) animated {
L0Log(@"window = %@, will be pinned to desktop = %d, was pinned to desktop = %d", c, pinned, [self isWindowKeptPinnedToDesktop:c]);
// BOOL wasPinned = [self isWindowKeptAfloat:c];
// TODO: make a badge for "Pinned to Desktop"
[c setLevel:(pinned)? kCGDesktopWindowLevel : NSNormalWindowLevel];
if (!pinned && [self isWindowOverlay:c] && !_settingOverlay)
[self setOverlay:NO forWindow:c animated:animated showBadgeAnimation:NO];
}
- (BOOL) isWindowKeptPinnedToDesktop:(NSWindow*) w {
return [w level] == kCGDesktopWindowLevel;
}
@end
@implementation NSApplication (Afloat)
- (void) afloat_sendEvent:(NSEvent*) evt {
unsigned mods = [evt modifierFlags] & NSDeviceIndependentModifierFlagsMask;
NSPoint ori;
NSRect frame;
Afloat* hub = [Afloat sharedInstance];
NSWindow* wnd;
if (mods == (NSCommandKeyMask | NSControlKeyMask)) {
switch ([evt type]) {
// The three-finger swipe gesture on a multitouch (MB Air/Pro) trackpad
#define kAfloatNSSwipeGestureEvent (31)
case kAfloatNSSwipeGestureEvent: {
NSWindow* w = [evt window];
if ([hub isWindowIgnoredByAfloat:w]) w = [hub currentWindow];
if (w) {
if ([evt deltaY] > 0)
[hub setKeptAfloat:YES forWindow:w showBadgeAnimation:YES];
else if ([evt deltaY] < 0)
[hub setKeptAfloat:NO forWindow:w showBadgeAnimation:YES];
return; // filter it
}
}
case NSLeftMouseDown:
case NSRightMouseDown:
return; // filter it
case NSLeftMouseDragged: {
wnd = [evt window];
if ([hub isWindowIgnoredByAfloat:wnd]) wnd = [hub currentWindow];
ori = [wnd frame].origin;
ori.x += [evt deltaX];
ori.y -= [evt deltaY];
[wnd setFrameOrigin:ori];
return; // filter it once done
}
case NSRightMouseDragged: {
wnd = [evt window];
if ([hub isWindowIgnoredByAfloat:wnd]) wnd = [hub currentWindow];
if (wnd && ([wnd styleMask] & NSResizableWindowMask)) {
NSSize minSize = [wnd minSize];
frame = [wnd frame];
frame.size.width += [evt deltaX];
frame.size.height += [evt deltaY];
if (frame.size.width < minSize.width)
frame.size.width = minSize.width;
if (frame.size.height < minSize.height)
frame.size.height = minSize.height;
else
frame.origin.y -= [evt deltaY];
[wnd setFrame:frame display:YES];
return; // filter it once done
}
}
case NSLeftMouseUp:
case NSRightMouseUp:
return; // filter it
case NSScrollWheel: {
wnd = [evt window];
if ([hub isWindowIgnoredByAfloat:wnd]) wnd = [hub currentWindow];
[hub setAlphaValueByDelta:([evt deltaY] * 0.10) forWindow:wnd animate:NO];
return; // filter it
}
}
}
// If we didn't return above, we return the event to its
// regular code path.
[self afloat_sendEvent:evt];
}
@end