/
StatusItemController.m
438 lines (380 loc) · 16.1 KB
/
StatusItemController.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
/***************************************************************************
* Copyright 2005-2009 Last.fm Ltd. *
* Copyright 2010 Max Howell <max@methylblue.com> *
* *
* 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 2 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, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Steet, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
#import "AutoDash.h"
#import "lastfm.h"
#import "NSDictionary+Track.h"
#import "ITunesListener.h"
#import "StatusItemController.h"
#import <Carbon/Carbon.h>
#import <WebKit/WebKit.h>
static bool scrobsub_fsref(FSRef* fsref)
{
OSStatus err = LSFindApplicationForInfo(kLSUnknownCreator, CFSTR("fm.last.Audioscrobbler"), NULL, fsref, NULL);
return err != kLSApplicationNotFoundErr;
}
static OSStatus MyHotKeyHandler(EventHandlerCallRef ref, EventRef e, void* userdata)
{
EventHotKeyID hkid;
GetEventParameter(e, kEventParamDirectObject, typeEventHotKeyID, NULL, sizeof(hkid), NULL, &hkid);
switch(hkid.id){
case 1:
[(StatusItemController*)userdata tag:userdata];
break;
case 2:
[(StatusItemController*)userdata share:userdata];
break;
}
return noErr;
}
static LSSharedFileListItemRef audioscrobbler_session_login_item(LSSharedFileListRef login_items_ref)
{
FSRef as_fsref;
if (!scrobsub_fsref(&as_fsref))
return NULL;
UInt32 seed;
NSArray *items = [(NSArray*)LSSharedFileListCopySnapshot(login_items_ref, &seed) autorelease];
for (id id in items){
FSRef fsref;
LSSharedFileListItemRef item = (LSSharedFileListItemRef)id;
if (LSSharedFileListItemResolve(item, 0, NULL, &fsref) == noErr)
if (FSCompareFSRefs(&as_fsref, &fsref) == noErr)
return item;
}
return NULL;
}
static NSString* downloads()
{
NSString* path = [NSHomeDirectory() stringByAppendingPathComponent:@"Downloads"];
BOOL isdir = false;
if ([[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isdir] && isdir)
return path;
return NSTemporaryDirectory();
}
@implementation StatusItemController
+(void)initialize
{
[[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary
dictionaryWithObject:[NSNumber numberWithBool:false]
forKey:@"AutoDash"]];
}
-(NSDictionary*)registrationDictionaryForGrowl
{
NSArray* all = [NSArray arrayWithObjects:
ASGrowlTrackStarted,
ASGrowlTrackPaused,
ASGrowlTrackResumed,
ASGrowlPlaylistEnded,
ASGrowlLoveTrackQuery,
ASGrowlAuthenticationRequired,
ASGrowlErrorCommunication,
ASGrowlCorrectionSuggestion,
nil];
NSArray* defaults = [NSArray arrayWithObjects:
ASGrowlTrackStarted,
ASGrowlTrackResumed,
ASGrowlPlaylistEnded,
ASGrowlLoveTrackQuery,
ASGrowlAuthenticationRequired,
ASGrowlErrorCommunication,
ASGrowlCorrectionSuggestion,
nil];
return [NSDictionary dictionaryWithObjectsAndKeys:
all, GROWL_NOTIFICATIONS_ALL,
defaults, GROWL_NOTIFICATIONS_DEFAULT,
nil];
}
-(void)awakeFromNib
{
status_item = [[[NSStatusBar systemStatusBar] statusItemWithLength:27] retain];
[status_item setHighlightMode:YES];
[status_item setImage:[NSImage imageNamed:@"icon.png"]];
[status_item setAlternateImage:[NSImage imageNamed:@"inverted_icon.png"]];
[status_item setEnabled:YES];
[status_item setMenu:menu];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(onPlayerInfo:)
name:@"playerInfo"
object:nil];
[GrowlApplicationBridge setGrowlDelegate:self];
if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"AutoDash"] boolValue] == true)
autodash = [[AutoDash alloc] init];
[NSApp setMainMenu:app_menu]; // so the close shortcut will work
/// Start at Login item
LSSharedFileListRef login_items_ref = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);
if(login_items_ref){
LSSharedFileListItemRef login_item = audioscrobbler_session_login_item(login_items_ref);
[start_at_login setState:login_item?NSOnState:NSOffState];
CFRelease(login_items_ref);
}
#if __AS_DEBUGGING__
[[menu itemAtIndex:[menu numberOfItems]-1] setTitle:@"Quit Debugscrobbler"];
#else
/// global shortcut
EventTypeSpec type;
type.eventClass = kEventClassKeyboard;
type.eventKind = kEventHotKeyPressed;
InstallApplicationEventHandler(&MyHotKeyHandler, 1, &type, self, NULL);
EventHotKeyID kid;
EventHotKeyRef kref;
kid.signature='htk1';
kid.id=1;
RegisterEventHotKey(kVK_ANSI_T, cmdKey+optionKey+controlKey, kid, GetApplicationEventTarget(), 0, &kref);
kid.signature='htk2';
kid.id=2;
RegisterEventHotKey(kVK_ANSI_S, cmdKey+optionKey+controlKey, kid, GetApplicationEventTarget(), 0, &kref);
#endif
lastfm = [[Lastfm alloc] initWithDelegate:self];
listener = [[ITunesListener alloc] initWithLastfm:lastfm];
}
-(void)dealloc
{
[sharewc release];
[listener release];
[lastfm release];
[autodash release];
[status_item release];
[super dealloc];
}
-(bool)autohide
{
return false;
}
-(void)onPlayerInfo:(NSNotification*)userData
{
static uint count = 0;
NSDictionary* dict = [userData userInfo];
uint transition = [[dict objectForKey:@"Transition"] unsignedIntValue];
NSString* name = [dict objectForKey:@"Name"];
uint const duration = [(NSNumber*)[dict objectForKey:@"Total Time"] longLongValue] / 1000;
NSString* notificationName = ASGrowlTrackResumed;
#define UPDATE_TITLE_MENU \
[status setTitle:[NSString stringWithFormat:@"%@ [%d:%02d]", name, duration/60, duration%60]];
switch(transition){
case TrackStarted:
[love setEnabled:true];
[love setTitle:@"Love"];
[share setEnabled:true];
[tag setEnabled:true];
notificationName = ASGrowlTrackStarted;
count++;
// fall through
case TrackResumed:{
UPDATE_TITLE_MENU
NSMutableString* desc = [[[dict objectForKey:@"Artist"] mutableCopy] autorelease];
[desc appendString:@"\n"];
[desc appendString:[dict objectForKey:@"Album"]];
[GrowlApplicationBridge notifyWithTitle:name
description:desc
notificationName:notificationName
iconData:[dict objectForKey:@"Album Art"]
priority:0
isSticky:false
clickContext:dict
identifier:ASGrowlTrackStarted];
break;}
case TrackPaused:
[status setTitle:[name stringByAppendingString:@" [paused]"]];
[GrowlApplicationBridge notifyWithTitle:@"Playback Paused"
description:[[dict objectForKey:@"Player Name"] stringByAppendingString:@" became paused"]
notificationName:ASGrowlTrackPaused
iconData:nil
priority:0
isSticky:true
clickContext:dict
identifier:ASGrowlTrackStarted];
break;
case PlaybackStopped:
[status setTitle:@"Ready"];
[love setEnabled:false];
[tag setEnabled:false];
[share setEnabled:false];
[love setTitle:@"Love"];
NSNumberFormatter* formatter = [[NSNumberFormatter alloc] init];
NSString* info = [NSString stringWithFormat:@"You played %@ tracks this session.",
[formatter stringFromNumber:[NSNumber numberWithUnsignedInt:count]]];
[formatter release];
count = 0;
[GrowlApplicationBridge notifyWithTitle:@"Playlist Ended"
description:info
notificationName:ASGrowlPlaylistEnded
iconData:nil
priority:0
isSticky:false
clickContext:nil];
break;
case TrackMetadataChanged:
UPDATE_TITLE_MENU
[GrowlApplicationBridge notifyWithTitle:@"Track Metadata Updated"
description:dict.prettyTitle
notificationName:ASGrowlSubmissionStatus
iconData:nil
priority:-1
isSticky:false
clickContext:nil];
break;
}
}
-(void)lastfm:(Lastfm*)lastfm requiresAuth:(NSURL*)url
{
if (![GrowlApplicationBridge isGrowlInstalled] || ![GrowlApplicationBridge isGrowlRunning]) {
[[NSWorkspace sharedWorkspace] openURL:url];
return;
}
[GrowlApplicationBridge notifyWithTitle:@"Authentication Required"
description:@"Before you can scrobble, Last.fm want you to approve this app at their website. Click here to open your browser at the authorisation page."
notificationName:ASGrowlAuthenticationRequired
iconData:nil
priority:1
isSticky:true
clickContext:[url absoluteString] // for some fucked up reason, this had to be a string
identifier:ASGrowlAuthenticationRequired];
}
-(void)lastfm:(Lastfm*)lastfm error:(NSString*)message
{
[GrowlApplicationBridge notifyWithTitle:@"Error Occurred :("
description:message
notificationName:ASGrowlErrorCommunication
iconData:nil
priority:2
isSticky:false
clickContext:nil];
}
-(void)lastfm:(Lastfm*)lastfm metadata:(NSDictionary*)metadata betterdata:(NSDictionary*)betterdata
{
[GrowlApplicationBridge notifyWithTitle:@"Suggested Metadata Correction"
description:betterdata.prettyTitle
notificationName:ASGrowlCorrectionSuggestion
iconData:nil
priority:-1
isSticky:false
clickContext:nil];
}
-(void)growlNotificationWasClicked:(id)dict
{
if ([dict isKindOfClass:[NSString class]])
{
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:dict]];
}
else if([[dict objectForKey:@"Notification Name"] isEqualToString:ASGrowlLoveTrackQuery])
{
if (listener.track.pid == [dict pid])
[self love:self];
else
[lastfm love:dict];
// need some kind of feedback
}
else
[[NSWorkspace sharedWorkspace] openURL:[Lastfm urlForTrack:[dict objectForKey:@"Name"]
by:[dict objectForKey:@"Artist"]]];
}
-(IBAction)love:(id)sender
{
[lastfm love:listener.track];
[love setEnabled:false];
[love setTitle:@"Loved"];
}
-(IBAction)tag:(id)sender
{
NSDictionary* t = listener.track;
NSURL* url = [Lastfm urlForTrack:t.title by:t.artist];
NSString* path = [[url path] stringByAppendingPathComponent:@"+tags"];
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:path relativeToURL:url]];
}
-(IBAction)share:(id)sender
{
if(!sharewc)
sharewc = [[ShareWindowController alloc] initWithWindowNibName:@"ShareWindow"];
[sharewc showWindow:self];
[sharewc setTrack:listener.track];
[sharewc setLastfm:lastfm];
[sharewc.window makeKeyWindow];
}
-(IBAction)startAtLogin:(id)sender
{
FSRef fsref;
if (!scrobsub_fsref(&fsref)) return;
LSSharedFileListRef login_items_ref = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);
if (login_items_ref == NULL) return;
LSSharedFileListItemRef item;
if (NSOffState == [sender state]){
item = LSSharedFileListInsertItemFSRef(login_items_ref,
kLSSharedFileListItemLast,
NULL, // name
NULL, // icon
&fsref,
NULL, NULL);
if (item){
[sender setState:NSOnState];
CFRelease(item);
}
}
else if (item = audioscrobbler_session_login_item(login_items_ref)){
LSSharedFileListItemRemove(login_items_ref, item);
[sender setState:NSOffState];
}
CFRelease(login_items_ref);
}
-(IBAction)installDashboardWidget:(id)sender
{
NSString* bz2 = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Last.fm.wdgt.tar.bz2"];
NSTask* task = [[NSTask alloc] init];
[task setLaunchPath:@"/usr/bin/tar"];
[task setCurrentDirectoryPath:downloads()];
[task setArguments:[NSArray arrayWithObjects:@"xf", bz2, nil]];
[task launch];
[task waitUntilExit];
[[NSWorkspace sharedWorkspace] openFile:[[task currentDirectoryPath] stringByAppendingPathComponent:@"Last.fm.wdgt"]];
[task release];
}
-(IBAction)activateAutoDash:(id)sender
{
if ([sender state] == NSOnState)
autodash = [[AutoDash alloc] init];
else
[autodash release];
}
-(IBAction)about:(id)sender
{
// http://www.cocoadev.com/index.pl?NSStatusItem
// LSUIElement screws up Window ordering
[NSApp activateIgnoringOtherApps:YES];
[NSApp orderFrontStandardAboutPanel:sender];
}
-(IBAction)moreRecentHistory:(id)sender
{
[[NSWorkspace sharedWorkspace] openURL:[Lastfm urlForUser:[lastfm username]]];
}
@end
@implementation ShareWindowController
@synthesize track;
@synthesize lastfm;
-(void)submit:(id)sender
{
[spinner startAnimation:self];
[lastfm share:track with:[username stringValue]];
[self close];
[spinner stopAnimation:self];
}
-(void)showWindow:(id)sender
{
[NSApp activateIgnoringOtherApps:YES]; //see above about:
[super showWindow:sender];
}
@end