-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAIHApplicationIconHerald.m
478 lines (427 loc) · 17.3 KB
/
AIHApplicationIconHerald.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
#import "AIHApplicationIconHerald.h"
#import <CommonCrypto/CommonDigest.h>
#define AIH_BADGE_HEIGHT_DIVISOR 2.7
#define AIH_BADGE_PRERENDERED_SIZE 40.0
#define AIH_BADGE_PRERENDERED_PADDING 8.0
#define AIH_BADGE_PRERENDERED_SHADOW_BLUR_RADIUS 3.0
static NSString *const AIHAnnouncementNotificationName = @"com.manytricks.AIHAnnouncementNotification";
static NSString *const AIHRequestNotificationName = @"com.manytricks.AIHRequestNotification";
static NSString *const AIHFormatKey = @"Format";
static NSString *const AIHUserNameHashKey = @"User";
NSString *const AIHBundleIdentifierKey = @"Identifier";
NSString *const AIHBadgeKey = @"Badge";
NSString *const AIHImageKey = @"Image";
static NSString *const AIHDisableAnnouncingUserDefaultKey = @"com.manytricks.AIHDisableAnnouncing";
static NSString *const AIHDisableListeningUserDefaultKey = @"com.manytricks.AIHDisableListening";
NSImage *_Nonnull AIHCreateBadgeImage(NSString *_Nonnull badge, NSColor *_Nullable textColor, NSColor *_Nullable backgroundColor, NSColor *_Nullable borderColor) {
NSImage *badgeImage = nil;
@autoreleasepool {
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[paragraphStyle setAlignment: NSTextAlignmentCenter];
[paragraphStyle setLineBreakMode: NSLineBreakByTruncatingMiddle];
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
(textColor ?: [NSColor whiteColor]), NSForegroundColorAttributeName,
[NSFont systemFontOfSize: AIH_BADGE_PRERENDERED_SIZE], NSFontAttributeName,
paragraphStyle, NSParagraphStyleAttributeName,
nil];
NSRect badgeBounds;
badgeBounds.origin = NSZeroPoint;
badgeBounds.size = [badge sizeWithAttributes: attributes];
if (NSIsEmptyRect(badgeBounds)) {
badgeBounds.size = NSMakeSize(AIH_BADGE_PRERENDERED_PADDING, AIH_BADGE_PRERENDERED_PADDING);
}
badgeBounds.size.width += AIH_BADGE_PRERENDERED_PADDING + AIH_BADGE_PRERENDERED_PADDING + AIH_BADGE_PRERENDERED_SHADOW_BLUR_RADIUS + AIH_BADGE_PRERENDERED_SHADOW_BLUR_RADIUS;
badgeBounds.size.height += AIH_BADGE_PRERENDERED_PADDING + AIH_BADGE_PRERENDERED_PADDING + AIH_BADGE_PRERENDERED_SHADOW_BLUR_RADIUS + AIH_BADGE_PRERENDERED_SHADOW_BLUR_RADIUS;
if (badgeBounds.size.width<badgeBounds.size.height) {
badgeBounds.size.width = badgeBounds.size.height;
} else {
badgeBounds.size.width += AIH_BADGE_PRERENDERED_PADDING + AIH_BADGE_PRERENDERED_PADDING;
CGFloat maximumWidth = badgeBounds.size.height * AIH_BADGE_HEIGHT_DIVISOR;
if (badgeBounds.size.width>maximumWidth) {
badgeBounds.size.width = maximumWidth;
}
}
badgeImage = [[NSImage alloc] initWithSize: badgeBounds.size];
[badgeImage lockFocus];
[NSGraphicsContext saveGraphicsState];
[(backgroundColor ?: [NSColor colorWithCalibratedRed: 1.0 green: 0.0 blue: 0.0 alpha: 0.9]) set];
NSShadow *shadow = [[NSShadow alloc] init];
[shadow setShadowOffset: NSMakeSize(0.0, -1.0)];
[shadow setShadowBlurRadius: AIH_BADGE_PRERENDERED_SHADOW_BLUR_RADIUS];
[shadow setShadowColor: [NSColor colorWithCalibratedWhite: 0.0 alpha: 0.4]];
[shadow set];
NSRect innerBadgeRect = NSInsetRect(badgeBounds, AIH_BADGE_PRERENDERED_SHADOW_BLUR_RADIUS, AIH_BADGE_PRERENDERED_SHADOW_BLUR_RADIUS);
[[NSBezierPath bezierPathWithRoundedRect: innerBadgeRect xRadius: innerBadgeRect.size.height * 0.5 yRadius: innerBadgeRect.size.height * 0.5] fill];
[NSGraphicsContext restoreGraphicsState];
if ((borderColor) || (NSAppKitVersionNumber<NSAppKitVersionNumber10_10)) {
[NSGraphicsContext saveGraphicsState];
[(borderColor ?: [NSColor whiteColor]) set];
CGFloat borderWidth = floor(innerBadgeRect.size.height * 0.05);
if (borderWidth<1) {
borderWidth = 1.0;
}
NSRect borderRect = NSInsetRect(innerBadgeRect, borderWidth * 0.5, borderWidth * 0.5);
NSBezierPath *borderPath = [NSBezierPath bezierPathWithRoundedRect: borderRect xRadius: borderRect.size.height * 0.5 yRadius: borderRect.size.height * 0.5];
[borderPath setLineWidth: borderWidth];
[borderPath stroke];
[NSGraphicsContext restoreGraphicsState];
}
[badge drawInRect: NSInsetRect(badgeBounds, AIH_BADGE_PRERENDERED_PADDING + AIH_BADGE_PRERENDERED_SHADOW_BLUR_RADIUS, AIH_BADGE_PRERENDERED_PADDING + AIH_BADGE_PRERENDERED_SHADOW_BLUR_RADIUS) withAttributes: attributes];
[badgeImage unlockFocus];
#if !__has_feature(objc_arc)
[paragraphStyle release];
[shadow release];
#endif
}
return badgeImage;
}
void AIHDrawBadgeImage(NSImage *_Nonnull badgeImage, NSRect iconRect, BOOL alignWithTopEdge, BOOL alignWithRightEdge) {
NSGraphicsContext *graphicsContext = [NSGraphicsContext currentContext];
NSImageInterpolation interpolationBackup = graphicsContext.imageInterpolation;
NSImageInterpolation interpolation = interpolationBackup;
if (@available(macOS 11, *)) {
interpolation = NSImageInterpolationMedium; // as of macOS 11.0.1, high interpolation screws up the badge image, so let's make do with medium
if (interpolation!=interpolationBackup) {
graphicsContext.imageInterpolation = interpolation;
}
}
NSSize badgeImageSize = [badgeImage size];
NSRect badgeRect;
badgeRect.size.height = iconRect.size.height / AIH_BADGE_HEIGHT_DIVISOR;
badgeRect.size.width = badgeImageSize.width * badgeRect.size.height / badgeImageSize.height;
badgeRect.origin = iconRect.origin;
if (alignWithTopEdge) {
badgeRect.origin.y += iconRect.size.height - badgeRect.size.height;
}
if (alignWithRightEdge) {
badgeRect.origin.x += iconRect.size.width - badgeRect.size.width;
}
[badgeImage drawInRect: badgeRect fromRect: NSZeroRect operation: NSCompositingOperationSourceOver fraction: 1.0];
if (interpolation!=interpolationBackup) {
graphicsContext.imageInterpolation = interpolationBackup;
}
}
void AIHDrawBadge(NSString *_Nonnull badge, NSColor *_Nullable textColor, NSColor *_Nullable backgroundColor, NSColor *_Nullable borderColor, NSRect iconRect, BOOL alignWithTopEdge, BOOL alignWithRightEdge) {
NSImage *badgeImage = AIHCreateBadgeImage(badge, textColor, backgroundColor, borderColor);
if (badgeImage) {
AIHDrawBadgeImage(badgeImage, iconRect, alignWithTopEdge, alignWithRightEdge);
#if !__has_feature(objc_arc)
[badgeImage release];
#endif
}
}
static NSString *_Nonnull AIHTransportStringFromData(NSData *_Nonnull data) {
return [data base64EncodedStringWithOptions: 0];
}
static NSString *_Nullable AIHUserNameHash(void) {
NSData *data = [NSUserName() dataUsingEncoding: NSUTF8StringEncoding];
if (data) {
unsigned char buffer[CC_SHA1_DIGEST_LENGTH];
CC_SHA1(data.bytes, (CC_LONG)data.length, buffer);
return AIHTransportStringFromData([NSData dataWithBytes: buffer length: CC_SHA1_DIGEST_LENGTH]);
}
return nil;
}
static NSDictionary *_Nullable AIHCreateTransportDictionary(NSDictionary *_Nullable iconDictionary, BOOL compressImage) {
NSMutableDictionary *transportDictionary = nil;
@autoreleasepool {
NSString *userNameHash = AIHUserNameHash();
if (userNameHash) {
NSString *bundleIdentifier = [iconDictionary objectForKey: AIHBundleIdentifierKey];
if ((bundleIdentifier) || (bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier])) {
transportDictionary = [[NSMutableDictionary alloc] init];
[transportDictionary setObject: @"1" forKey: AIHFormatKey];
[transportDictionary setObject: userNameHash forKey: AIHUserNameHashKey];
[transportDictionary setObject: bundleIdentifier forKey: AIHBundleIdentifierKey];
NSImage *image = [iconDictionary objectForKey: AIHImageKey];
if (image) {
if (compressImage) {
NSData *imageData = [image TIFFRepresentationUsingCompression: NSTIFFCompressionLZW factor: 0];
if (imageData) {
[transportDictionary setObject: AIHTransportStringFromData(imageData) forKey: AIHImageKey];
} else {
NSLog(@"[AIH] cannot compress image");
}
} else {
[transportDictionary setObject: image forKey: AIHImageKey];
}
}
NSString *badge = [iconDictionary objectForKey: AIHBadgeKey];
if ((badge) && (![badge isEqualToString: @"0"])) {
[transportDictionary setObject: badge forKey: AIHBadgeKey];
}
} else {
NSLog(@"[AIH] cannot determine bundle identifier");
}
} else {
NSLog(@"[AIH] cannot determine user name");
}
}
return transportDictionary;
}
static BOOL AIHProcessTransportDictionary(NSDictionary *_Nonnull transportDictionary, NSString *_Nullable *_Nullable bundleIdentifierPointer, NSImage *_Nullable *_Nullable imagePointer, NSString *_Nullable *_Nullable badgePointer, NSImage *_Nullable *_Nullable compositeIconPointer) {
NSString *bundleIdentifier = [transportDictionary objectForKey: AIHBundleIdentifierKey];
if (bundleIdentifier) {
NSImage *compositeIcon = nil;
id image = [transportDictionary objectForKey: AIHImageKey];
if ([image isKindOfClass: [NSString class]]) {
NSData *imageData = [[NSData alloc] initWithBase64EncodedString: image options: 0];
if (imageData) {
image = [[NSImage alloc] initWithData: imageData];
if (image) {
#if !__has_feature(objc_arc)
[image autorelease];
#endif
} else {
NSLog(@"[AIH] cannot decompress image");
}
#if !__has_feature(objc_arc)
[imageData release];
#endif
} else {
image = nil;
NSLog(@"[AIH] cannot decode image");
}
}
NSString *badge = [transportDictionary objectForKey: AIHBadgeKey];
if (badge) {
NSImage *baseIcon = ((image) ? image : [[[NSRunningApplication runningApplicationsWithBundleIdentifier: bundleIdentifier] firstObject] icon]);
if (baseIcon) {
NSImage *badgeImage = AIHCreateBadgeImage(badge, nil, nil, nil);
compositeIcon = [NSImage imageWithSize: [baseIcon size] flipped: NO drawingHandler: ^(NSRect targetRect) {
[baseIcon drawInRect: targetRect fromRect: NSZeroRect operation: NSCompositingOperationSourceOver fraction: 1.0];
AIHDrawBadgeImage(badgeImage, targetRect, YES, YES);
return YES;
}];
#if !__has_feature(objc_arc)
[badgeImage release];
#endif
} else {
NSLog(@"[AIH] cannot identify base icon");
}
}
if (bundleIdentifierPointer) {
(*bundleIdentifierPointer) = bundleIdentifier;
}
if (imagePointer) {
(*imagePointer) = image;
}
if (badgePointer) {
(*badgePointer) = badge;
}
if (compositeIconPointer) {
(*compositeIconPointer) = ((compositeIcon) ? compositeIcon : image);
}
return YES;
}
NSLog(@"[AIH] missing bundle identifier");
return NO;
}
static void AIHPostNotification(NSString *_Nonnull name, NSString *_Nullable object) {
[[NSDistributedNotificationCenter defaultCenter] postNotificationName: name object: object userInfo: nil options: NSNotificationDeliverImmediately | NSNotificationPostToAllSessions];
}
@interface AIHSerialQueueOwner: NSObject
{
dispatch_queue_t _serialQueue;
}
@end
@implementation AIHSerialQueueOwner
- (instancetype)init {
self = [super init];
if (self) {
_serialQueue = dispatch_queue_create(NULL, DISPATCH_QUEUE_SERIAL);
}
return self;
}
#if !__has_feature(objc_arc) || OS_OBJECT_HAVE_OBJC_SUPPORT==0
- (void)dealloc {
if (_serialQueue) {
dispatch_release(_serialQueue);
}
#if !__has_feature(objc_arc)
[super dealloc];
#endif
}
#endif
@end
@interface AIHAnnouncer: AIHSerialQueueOwner
{
NSString *_latestTransportString;
}
@end
@implementation AIHAnnouncer
+ (AIHAnnouncer *)defaultAnnouncer {
static AIHAnnouncer *staticDefaultAnnouncer = nil;
static dispatch_once_t staticDefaultAnnouncerOnceToken;
dispatch_once(&staticDefaultAnnouncerOnceToken, ^{
staticDefaultAnnouncer = [[self alloc] init];
});
return staticDefaultAnnouncer;
}
- (instancetype)init {
self = [super init];
if (self) {
[[NSDistributedNotificationCenter defaultCenter] addObserver: self selector: @selector(reannounce:) name: AIHRequestNotificationName object: nil];
}
return self;
}
- (void)announce: (NSDictionary *_Nullable)iconDictionary {
if (![[NSUserDefaults standardUserDefaults] boolForKey: AIHDisableAnnouncingUserDefaultKey]) {
dispatch_async(_serialQueue, ^{
NSDictionary *transportDictionary = AIHCreateTransportDictionary(iconDictionary, YES);
if (transportDictionary) {
@autoreleasepool {
NSError *error = nil;
NSData *transportData = [NSJSONSerialization dataWithJSONObject: transportDictionary options: 0 error: &error];
if (transportData) {
NSString *transportString = [[NSString alloc] initWithData: transportData encoding: NSUTF8StringEncoding];
if (transportString) {
#if !__has_feature(objc_arc)
[_latestTransportString release];
#endif
_latestTransportString = transportString;
AIHPostNotification(AIHAnnouncementNotificationName, _latestTransportString);
} else {
NSLog(@"[AIH] cannot encode");
}
} else {
NSLog(@"[AIH] cannot serialize: %@", error);
}
}
#if !__has_feature(objc_arc)
[transportDictionary release];
#endif
}
});
}
}
- (void)reannounce: (NSNotification *_Nullable)notification {
if (![[NSUserDefaults standardUserDefaults] boolForKey: AIHDisableAnnouncingUserDefaultKey]) {
dispatch_async(_serialQueue, ^{
AIHPostNotification(AIHAnnouncementNotificationName, _latestTransportString);
});
}
}
- (void)dealloc {
[[NSDistributedNotificationCenter defaultCenter] removeObserver: self];
#if !__has_feature(objc_arc)
[_latestTransportString release];
[super dealloc];
#endif
}
@end
@interface AIHListener: AIHSerialQueueOwner
{
AIHListeningBlock _listeningBlock;
}
@end
@implementation AIHListener
+ (AIHListener *)defaultListener {
static AIHListener *staticDefaultListener = nil;
static dispatch_once_t staticDefaultListenerOnceToken;
dispatch_once(&staticDefaultListenerOnceToken, ^{
staticDefaultListener = [[self alloc] init];
});
return staticDefaultListener;
}
- (void)setListeningBlock: (AIHListeningBlock _Nullable)listeningBlock {
dispatch_sync(_serialQueue, ^{
BOOL didListen = NO;
if (_listeningBlock) {
#if !__has_feature(objc_arc)
[_listeningBlock release];
#endif
didListen = YES;
}
_listeningBlock = [listeningBlock copy];
if (_listeningBlock) {
if (!didListen) {
[[NSDistributedNotificationCenter defaultCenter] addObserver: self selector: @selector(listen:) name: AIHAnnouncementNotificationName object: nil suspensionBehavior: NSNotificationSuspensionBehaviorDeliverImmediately];
}
AIHPostNotification(AIHRequestNotificationName, nil);
} else if (didListen) {
[[NSDistributedNotificationCenter defaultCenter] removeObserver: self];
}
});
}
- (void)listen: (NSNotification *_Nullable)notification {
if (![[NSUserDefaults standardUserDefaults] boolForKey: AIHDisableListeningUserDefaultKey]) {
NSString *transportString = [notification object];
if ([transportString length]>0) {
dispatch_async(_serialQueue, ^{
if (_listeningBlock) {
@autoreleasepool {
NSData *transportData = [transportString dataUsingEncoding: NSUTF8StringEncoding];
if (transportData) {
NSError *error = nil;
NSDictionary *transportDictionary = [NSJSONSerialization JSONObjectWithData: transportData options: 0 error: &error];
if (transportDictionary) {
NSString *userNameHash = [transportDictionary objectForKey: AIHUserNameHashKey];
if ((userNameHash) && [AIHUserNameHash() isEqualToString: userNameHash]) {
NSString *bundleIdentifier;
NSImage *image;
NSString *badge;
NSImage *compositeIcon;
if (AIHProcessTransportDictionary(transportDictionary, &bundleIdentifier, &image, &badge, &compositeIcon)) {
_listeningBlock(bundleIdentifier, image, badge, compositeIcon);
}
}
} else {
NSLog(@"[AIH] cannot deserialize: %@", error);
}
} else {
NSLog(@"[AIH] cannot decode");
}
}
}
});
}
}
}
- (void)dealloc {
if (_listeningBlock) {
[[NSDistributedNotificationCenter defaultCenter] removeObserver: self];
#if !__has_feature(objc_arc)
[_listeningBlock release];
#endif
}
#if !__has_feature(objc_arc)
[super dealloc];
#endif
}
@end
void AIHAnnounceBadgeCount(NSInteger count) {
@autoreleasepool {
[[AIHAnnouncer defaultAnnouncer] announce: ((count==0) ? nil : [NSDictionary dictionaryWithObject: [NSString stringWithFormat: @"%ld", (long)count] forKey: AIHBadgeKey])];
}
}
void AIHAnnounceBadge(NSString *_Nullable badge) {
@autoreleasepool {
[[AIHAnnouncer defaultAnnouncer] announce: ((badge) ? [NSDictionary dictionaryWithObject: badge forKey: AIHBadgeKey] : nil)];
}
}
void AIHAnnounceImage(NSImage *_Nullable image) {
@autoreleasepool {
[[AIHAnnouncer defaultAnnouncer] announce: ((image) ? [NSDictionary dictionaryWithObject: image forKey: AIHImageKey] : nil)];
}
}
void AIHAnnounceIcon(NSDictionary *_Nullable iconDictionary) {
[[AIHAnnouncer defaultAnnouncer] announce: iconDictionary];
}
void AIHSetListeningBlock(AIHListeningBlock _Nullable listeningBlock) {
[[AIHListener defaultListener] setListeningBlock: listeningBlock];
}
NSImage *_Nullable AIHCreateCompositeIcon(NSDictionary *_Nonnull iconDictionary) {
NSImage *compositeIcon = nil;
@autoreleasepool {
NSDictionary *transportDictionary = AIHCreateTransportDictionary(iconDictionary, NO);
if (transportDictionary) {
AIHProcessTransportDictionary(transportDictionary, NULL, NULL, NULL, &compositeIcon);
#if !__has_feature(objc_arc)
[transportDictionary release];
[compositeIcon retain];
#endif
}
}
return compositeIcon;
}