Yay, no more leaks.
[MenuTunes.git] / MenuTunes.m
1 //
2 //  MenuTunes.m
3 //
4 //  iThink Software, Copyright 2002
5 //
6 //
7
8 /*
9 Things to do:
10 ¥ Radio mode makes things act oddly
11 ¥ Make preferences window pretty
12 ¥ Hot Keys
13     - hot keys can't be set when NSBGOnly is on. The window is not key,
14       so the KeyBroadcaster does not pick up key combos
15     - going to need a different way of defining key combos
16 ¥ Optimize, this thing is big and slow :(
17 ¥ Apple Events! Apple Events! Apple Events!
18 */
19
20 #import "MenuTunes.h"
21 #import "MenuTunesView.h"
22 #import "PreferencesController.h"
23 #import "HotKeyCenter.h"
24 #import "StatusWindowController.h"
25
26 @implementation MenuTunes
27
28 - (void)applicationDidFinishLaunching:(NSNotification *)note
29 {
30     if (![[NSUserDefaults standardUserDefaults] objectForKey:@"menu"])
31     {
32         [[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"Play/Pause", @"Next Track", @"Previous Track", @"Fast Forward", @"Rewind", @"<separator>", @"Upcoming Songs", @"Playlists", @"<separator>", @"PreferencesÉ", @"Quit", @"<separator>", @"Current Track Info", nil] forKey:@"menu"];
33     }
34     
35     menu = [[NSMenu alloc] initWithTitle:@""];
36     iTunesPSN = [self iTunesPSN]; //Get PSN of iTunes if it's running
37     
38     if (!((iTunesPSN.highLongOfPSN == kNoProcess) && (iTunesPSN.lowLongOfPSN == 0)))
39     {
40         [self rebuildMenu];
41         refreshTimer = [NSTimer scheduledTimerWithTimeInterval:3.5 
42 target:self selector:@selector(timerUpdate) userInfo:nil repeats:YES];
43     }
44     else
45     {
46         menu = [[NSMenu alloc] initWithTitle:@""];
47         [[menu addItemWithTitle:@"Open iTunes" action:@selector(openiTunes:) keyEquivalent:@""] setTarget:self];
48         [[menu addItemWithTitle:@"Preferences" action:@selector(showPreferences:) keyEquivalent:@""] setTarget:self];
49         [[menu addItemWithTitle:@"Quit" action:@selector(quitMenuTunes:) keyEquivalent:@""] setTarget:self];
50         [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(iTunesLaunched:) name:NSWorkspaceDidLaunchApplicationNotification object:nil];
51         refreshTimer = nil;
52     }
53     
54     statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength];
55     [statusItem setImage:[NSImage imageNamed:@"menu.tiff"]];
56     [statusItem setHighlightMode:YES];
57     [statusItem setMenu:menu];
58     [statusItem retain];
59     view = [[MenuTunesView alloc] initWithFrame:[[statusItem view] frame]];
60     //[statusItem setView:view];
61 }
62
63 - (void)applicationWillTerminate:(NSNotification *)note
64 {
65     [self clearHotKeys];
66     [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
67 }
68
69 - (void)dealloc
70 {
71     if (refreshTimer)
72     {
73         [refreshTimer invalidate];
74     }
75     [statusItem release];
76     [menu release];
77     [view release];
78     [super dealloc];
79 }
80
81 //Recreate the status item menu
82 - (void)rebuildMenu
83 {
84     NSArray *myMenu = [[NSUserDefaults standardUserDefaults] arrayForKey:@"menu"];
85     int i;
86     trackInfoIndex = -1;
87     
88     didHaveAlbumName = (([[self runScriptAndReturnResult:@"return album of current track"] length] > 0) ? YES : NO);
89     
90     while ([menu numberOfItems] > 0)
91     {
92         [menu removeItemAtIndex:0];
93     }
94     
95     playPauseMenuItem = nil;
96     upcomingSongsItem = nil;
97     playlistItem = nil;
98     [playlistMenu release];
99     playlistMenu = nil;
100     eqItem = nil;
101     [eqMenu release];
102     eqMenu = nil;
103     
104     for (i = 0; i < [myMenu count]; i++)
105     {
106         NSString *item = [myMenu objectAtIndex:i];
107         if ([item isEqualToString:@"Play/Pause"])
108         {
109             playPauseMenuItem = [menu addItemWithTitle:@"Play" action:@selector(playPause:) keyEquivalent:@""];
110             [playPauseMenuItem setTarget:self];
111         }
112         else if ([item isEqualToString:@"Next Track"])
113         {
114             [[menu addItemWithTitle:@"Next Track" action:@selector(nextSong:) keyEquivalent:@""] setTarget:self];
115         }
116         else if ([item isEqualToString:@"Previous Track"])
117         {
118             [[menu addItemWithTitle:@"Previous Track" action:@selector(prevSong:) keyEquivalent:@""] setTarget:self];
119         }
120         else if ([item isEqualToString:@"Fast Forward"])
121         {
122             [[menu addItemWithTitle:@"Fast Forward" action:@selector(fastForward:) keyEquivalent:@""] setTarget:self];
123         }
124         else if ([item isEqualToString:@"Rewind"])
125         {
126             [[menu addItemWithTitle:@"Rewind" action:@selector(rewind:) keyEquivalent:@""] setTarget:self];
127         }
128         else if ([item isEqualToString:@"Upcoming Songs"])
129         {
130             upcomingSongsItem = [menu addItemWithTitle:@"Upcoming Songs" action:NULL keyEquivalent:@""];
131         }
132         else if ([item isEqualToString:@"Playlists"])
133         {
134             playlistItem = [menu addItemWithTitle:@"Playlists" action:NULL keyEquivalent:@""];
135         }
136         else if ([item isEqualToString:@"EQ Presets"])
137         {
138             eqItem = [menu addItemWithTitle:@"EQ Presets" action:NULL keyEquivalent:@""];
139         }
140         else if ([item isEqualToString:@"PreferencesÉ"])
141         {
142             [[menu addItemWithTitle:@"PreferencesÉ" action:@selector(showPreferences:) keyEquivalent:@""] setTarget:self];
143         }
144         else if ([item isEqualToString:@"Quit"])
145         {
146             [[menu addItemWithTitle:@"Quit" action:@selector(quitMenuTunes:) keyEquivalent:@""] setTarget:self];
147         }
148         else if ([item isEqualToString:@"Current Track Info"])
149         {
150             trackInfoIndex = [menu numberOfItems];
151             [menu addItemWithTitle:@"No Song" action:NULL keyEquivalent:@""];
152         }
153         else if ([item isEqualToString:@"<separator>"])
154         {
155             [menu addItem:[NSMenuItem separatorItem]];
156         }
157     }
158     
159     curTrackIndex = -1; //Force update of everything
160     [self timerUpdate]; //Updates dynamic info in the menu
161     
162     [self clearHotKeys];
163     [self setupHotKeys];
164 }
165
166 //Updates the menu with current player state, song, and upcoming songs
167 - (void)updateMenu
168 {
169     NSString *curSongName, *curAlbumName;
170     NSMenuItem *menuItem;
171     
172     if ((iTunesPSN.highLongOfPSN == kNoProcess) && (iTunesPSN.lowLongOfPSN == 0))
173     {
174         return;
175     }
176     
177     //Get the current track name and album.
178     curSongName = [self runScriptAndReturnResult:@"return name of current track"];
179     curAlbumName = [self runScriptAndReturnResult:@"return album of current track"];
180     
181     if (upcomingSongsItem)
182     {
183         [self rebuildUpcomingSongsMenu];
184     }
185     if (playlistItem)
186     {
187         [self rebuildPlaylistMenu];
188     }
189     if (eqItem)
190     {
191         [self rebuildEQPresetsMenu];
192     }
193     
194     if ([curSongName length] > 0)
195     {
196         int index = [menu indexOfItemWithTitle:@"Now Playing"];
197         
198         if (index > -1)
199         {
200             [menu removeItemAtIndex:index + 1];
201             if (didHaveAlbumName)
202             {
203                 [menu removeItemAtIndex:index + 1];
204             }
205         }
206         
207         if ([curAlbumName length] > 0)
208         {
209             menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@"  %@", curAlbumName] action:NULL keyEquivalent:@""];
210             [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
211             [menuItem release];
212         }
213         
214         menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@"  %@", curSongName] action:NULL keyEquivalent:@""];
215         [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
216         [menuItem release];
217         
218         if (index == -1)
219         {
220             menuItem = [[NSMenuItem alloc] initWithTitle:@"Now Playing" action:NULL keyEquivalent:@""];
221             [menu removeItemAtIndex:[menu indexOfItemWithTitle:@"No Song"]];
222             [menu insertItem:menuItem atIndex:trackInfoIndex];
223             [menuItem release];
224         }
225     }
226     else if ([menu indexOfItemWithTitle:@"No Song"] == -1)
227     {
228         [menu removeItemAtIndex:trackInfoIndex];
229         [menu removeItemAtIndex:trackInfoIndex];
230         if (didHaveAlbumName)
231         {
232             [menu removeItemAtIndex:trackInfoIndex];
233         }
234         menuItem = [[NSMenuItem alloc] initWithTitle:@"No Song" action:NULL keyEquivalent:@""];
235         [menu insertItem:menuItem atIndex:trackInfoIndex];
236         [menuItem release];
237     }
238     
239     didHaveAlbumName = (([curAlbumName length] > 0) ? YES : NO);
240 }
241
242 //Rebuild the upcoming songs submenu. Can be improved a lot.
243 - (void)rebuildUpcomingSongsMenu
244 {
245     int numSongs = [[self runScriptAndReturnResult:@"return number of tracks in current playlist"] intValue];
246     int numSongsInAdvance = [[NSUserDefaults standardUserDefaults] integerForKey:@"SongsInAdvance"];
247     
248     if (numSongs > 0)
249     {
250         int curTrack = [[self runScriptAndReturnResult:@"return index of current track"] intValue];
251         int i;
252         
253         [upcomingSongsMenu release];
254         upcomingSongsMenu = [[NSMenu alloc] initWithTitle:@""];
255         
256         for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++)
257         {
258             if (i <= numSongs)
259             {
260                 NSString *curSong = [self runScriptAndReturnResult:[NSString stringWithFormat:@"return name of track %i of current playlist", i]];
261                 NSMenuItem *songItem;
262                 songItem = [[NSMenuItem alloc] initWithTitle:curSong action:@selector(playTrack:) keyEquivalent:@""];
263                 [songItem setTarget:self];
264                 [songItem setEnabled:YES];
265                 [songItem setRepresentedObject:[NSNumber numberWithInt:i]];
266                 [upcomingSongsMenu addItem:songItem];
267                 [songItem release];
268             }
269             else
270             {
271                 [upcomingSongsMenu addItemWithTitle:@"End of playlist." action:NULL keyEquivalent:@""];
272                 break;
273             }
274         }
275         [upcomingSongsItem setSubmenu:upcomingSongsMenu];
276         [upcomingSongsItem setEnabled:YES];
277     }
278 }
279
280 - (void)rebuildPlaylistMenu
281 {
282     int numPlaylists = [[self runScriptAndReturnResult:@"return number of playlists"] intValue];
283     int i, curPlaylist = [[self runScriptAndReturnResult:@"return index of current playlist"] intValue];
284     
285     if (playlistMenu && (numPlaylists == [playlistMenu numberOfItems]))
286         return;
287     
288     [playlistMenu release];
289     playlistMenu = [[NSMenu alloc] initWithTitle:@""];
290     
291     for (i = 1; i <= numPlaylists; i++)
292     {
293         NSString *playlistName = [self runScriptAndReturnResult:[NSString stringWithFormat:@"return name of playlist %i", i]];
294         NSMenuItem *tempItem;
295         tempItem = [[NSMenuItem alloc] initWithTitle:playlistName action:@selector(selectPlaylist:) keyEquivalent:@""];
296         [tempItem setTarget:self];
297         [tempItem setRepresentedObject:[NSNumber numberWithInt:i]];
298         [playlistMenu addItem:tempItem];
299         [tempItem release];
300     }
301     [playlistItem setSubmenu:playlistMenu];
302     
303     if (curPlaylist)
304     {
305         [[playlistMenu itemAtIndex:curPlaylist - 1] setState:NSOnState];
306     }
307 }
308
309 //Build a menu with the list of all available EQ presets
310 - (void)rebuildEQPresetsMenu
311 {
312     int numSets = [[self runScriptAndReturnResult:@"return number of EQ presets"] intValue];
313     int i;
314     
315     if (eqMenu && (numSets == [eqMenu numberOfItems]))
316         return;
317     
318     [eqMenu release];
319     eqMenu = [[NSMenu alloc] initWithTitle:@""];
320     
321     for (i = 1; i <= numSets; i++)
322     {
323         NSString *setName = [self runScriptAndReturnResult:[NSString stringWithFormat:@"return name of EQ preset %i", i]];
324         NSMenuItem *tempItem;
325         tempItem = [[NSMenuItem alloc] initWithTitle:setName action:@selector(selectEQPreset:) keyEquivalent:@""];
326         [tempItem setTarget:self];
327         [tempItem setRepresentedObject:[NSNumber numberWithInt:i]];
328         [eqMenu addItem:tempItem];
329         [tempItem release];
330     }
331     [eqItem setSubmenu:eqMenu];
332     
333     [[eqMenu itemAtIndex:[[self runScriptAndReturnResult:@"return index of current EQ preset"] intValue] - 1] setState:NSOnState];
334 }
335
336 - (void)clearHotKeys
337 {
338     [[HotKeyCenter sharedCenter] removeHotKey:@"PlayPause"];
339     [[HotKeyCenter sharedCenter] removeHotKey:@"NextTrack"];
340     [[HotKeyCenter sharedCenter] removeHotKey:@"PrevTrack"];
341     [[HotKeyCenter sharedCenter] removeHotKey:@"TrackInfo"];
342     [[HotKeyCenter sharedCenter] removeHotKey:@"UpcomingSongs"];
343 }
344
345 - (void)setupHotKeys
346 {
347     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
348     
349     if ([defaults objectForKey:@"PlayPause"] != nil)
350     {
351         [[HotKeyCenter sharedCenter] addHotKey:@"PlayPause"
352                 combo:[defaults keyComboForKey:@"PlayPause"]
353                 target:self action:@selector(playPause:)];
354     }
355     
356     if ([defaults objectForKey:@"NextTrack"] != nil)
357     {
358         [[HotKeyCenter sharedCenter] addHotKey:@"NextTrack"
359                 combo:[defaults keyComboForKey:@"NextTrack"]
360                 target:self action:@selector(nextSong:)];
361     }
362     
363     if ([defaults objectForKey:@"PrevTrack"] != nil)
364     {
365         [[HotKeyCenter sharedCenter] addHotKey:@"PrevTrack"
366                 combo:[defaults keyComboForKey:@"PrevTrack"]
367                 target:self action:@selector(prevSong:)];
368     }
369     
370     if ([defaults objectForKey:@"TrackInfo"] != nil)
371     {
372         [[HotKeyCenter sharedCenter] addHotKey:@"TrackInfo"
373                 combo:[defaults keyComboForKey:@"TrackInfo"]
374                 target:self action:@selector(showCurrentTrackInfo)];
375     }
376     
377     if ([defaults objectForKey:@"UpcomingSongs"] != nil)
378     {
379         [[HotKeyCenter sharedCenter] addHotKey:@"UpcomingSongs"
380                combo:[defaults keyComboForKey:@"UpcomingSongs"]
381                target:self action:@selector(showUpcomingSongs)];
382     }
383 }
384
385 //Runs an AppleScript and returns the result as an NSString after stripping quotes, if needed. It takes in script and automatically adds the tell iTunes and end tell statements.
386 - (NSString *)runScriptAndReturnResult:(NSString *)script
387 {
388     AEDesc scriptDesc, resultDesc;
389     Size length;
390     NSString *result;
391     Ptr buffer;
392     ComponentInstance myComponent = OpenDefaultComponent(kOSAComponentType, kAppleScriptSubtype);
393     
394     script = [NSString stringWithFormat:@"tell application \"iTunes\"\n%@\nend tell", script];
395     
396     AECreateDesc(typeChar, [script cString], [script cStringLength], 
397 &scriptDesc);
398     
399     OSADoScript(myComponent, &scriptDesc, kOSANullScript, typeChar, kOSAModeCanInteract, &resultDesc);
400     
401     length = AEGetDescDataSize(&resultDesc);
402     buffer = malloc(length);
403     
404     AEGetDescData(&resultDesc, buffer, length);
405     AEDisposeDesc(&scriptDesc);
406     AEDisposeDesc(&resultDesc);
407     CloseComponent(myComponent);
408     result = [NSString stringWithCString:buffer length:length];
409     if (![result isEqualToString:@""] &&
410         ([result characterAtIndex:0] == '\"') &&
411         ([result characterAtIndex:[result length] - 1] == '\"'))
412     {
413         result = [result substringWithRange:NSMakeRange(1, [result length] - 2)];
414     }
415     free(buffer);
416     buffer = NULL;
417     return result;
418 }
419
420 //Called when the timer fires.
421 - (void)timerUpdate
422 {
423     int pid;
424     
425     if (GetProcessPID(&iTunesPSN, &pid) == noErr)
426     {
427         int trackPlayingIndex = [[self runScriptAndReturnResult:@"return index of current track"] intValue];
428         
429         if (trackPlayingIndex != curTrackIndex)
430         {
431             [self updateMenu];
432             curTrackIndex = trackPlayingIndex;
433         }
434         
435         //Update Play/Pause menu item
436         if (playPauseMenuItem)
437         {
438             if ([[self runScriptAndReturnResult:@"return player state"] isEqualToString:@"playing"])
439             {
440                 [playPauseMenuItem setTitle:@"Pause"];
441             }
442             else
443             {
444                 [playPauseMenuItem setTitle:@"Play"];
445             }
446         }
447     }
448     else
449     {
450         [menu release];
451         menu = [[NSMenu alloc] initWithTitle:@""];
452         [[menu addItemWithTitle:@"Open iTunes" action:@selector(openiTunes:) keyEquivalent:@""] setTarget:self];
453         [[menu addItemWithTitle:@"Preferences" action:@selector(showPreferences:) keyEquivalent:@""] setTarget:self];
454         [[menu addItemWithTitle:@"Quit" action:@selector(quitMenuTunes:) keyEquivalent:@""] setTarget:self];
455         [statusItem setMenu:menu];
456         
457         [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(iTunesLaunched:) name:NSWorkspaceDidLaunchApplicationNotification object:nil];
458         [refreshTimer invalidate];
459         refreshTimer = nil;
460         [self clearHotKeys];
461     }
462 }
463
464 - (void)iTunesLaunched:(NSNotification *)note
465 {
466     NSDictionary *info = [note userInfo];
467     
468     iTunesPSN.highLongOfPSN = [[info objectForKey:@"NSApplicationProcessSerialNumberHigh"] longValue];
469     iTunesPSN.lowLongOfPSN = [[info objectForKey:@"NSApplicationProcessSerialNumberLow"] longValue];
470     
471     //Restart the timer
472     refreshTimer = [NSTimer scheduledTimerWithTimeInterval:3.5 target:self selector:@selector(timerUpdate) userInfo:nil repeats:YES]; 
473     
474     [self rebuildMenu]; //Rebuild the menu since no songs will be playing
475     [statusItem setMenu:menu]; //Set the menu back to the main one
476     [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
477 }
478
479 //Return the PSN of iTunes, if it's running
480 - (ProcessSerialNumber)iTunesPSN
481 {
482     ProcessSerialNumber procNum;
483     procNum.highLongOfPSN = kNoProcess;
484     procNum.lowLongOfPSN = 0;
485     
486     while ( (GetNextProcess(&procNum) == noErr) ) 
487     {
488         CFStringRef procName;
489         if ( (CopyProcessName(&procNum, &procName) == noErr) )
490         {
491             if ([(NSString *)procName isEqualToString:@"iTunes"])
492             {
493                 return procNum;
494             }
495             [(NSString *)procName release];
496         }
497     }
498     return procNum;
499 }
500
501 //Send an AppleEvent with a given event ID
502 - (void)sendAEWithEventClass:(AEEventClass)eventClass 
503 andEventID:(AEEventID)eventID
504 {
505     OSType iTunesType = 'hook';
506     AppleEvent event, reply;
507     
508     AEBuildAppleEvent(eventClass, eventID, typeApplSignature, &iTunesType, sizeof(iTunesType), kAutoGenerateReturnID, kAnyTransactionID, &event, NULL, "");
509     
510     AESend(&event, &reply, kAENoReply, kAENormalPriority, kAEDefaultTimeout, nil, nil);
511     AEDisposeDesc(&event);
512     AEDisposeDesc(&reply);
513 }
514
515 //
516 // Selectors - called from status item menu
517 //
518
519 - (void)playTrack:(id)sender
520 {
521     [self runScriptAndReturnResult:[NSString stringWithFormat:@"play track %i of current playlist", [[sender representedObject] intValue]]];
522     [self updateMenu];
523 }
524
525 - (void)selectPlaylist:(id)sender
526 {
527     int playlist = [[sender representedObject] intValue];
528     [self runScriptAndReturnResult:[NSString stringWithFormat:@"play playlist %i", playlist]];
529     [[playlistMenu itemAtIndex:playlist - 1] setState:NSOnState];
530     [self updateMenu];
531 }
532
533 - (void)selectEQPreset:(id)sender
534 {
535     int curSet = [[self runScriptAndReturnResult:@"return index of current EQ preset"] intValue];
536     int item = [[sender representedObject] intValue];
537     [self runScriptAndReturnResult:[NSString stringWithFormat:@"set current EQ preset to EQ preset %i", item]];
538     [self runScriptAndReturnResult:@"set EQ enabled to 1"];
539     [[eqMenu itemAtIndex:curSet - 1] setState:NSOffState];
540     [[eqMenu itemAtIndex:item - 1] setState:NSOnState];
541 }
542
543 - (void)playPause:(id)sender
544 {
545     NSString *state = [self runScriptAndReturnResult:@"return player state"];
546     if ([state isEqualToString:@"playing"])
547     {
548         [self sendAEWithEventClass:'hook' andEventID:'Paus'];
549         [playPauseMenuItem setTitle:@"Play"];
550     }
551     else if ([state isEqualToString:@"fast forwarding"] || [state 
552 isEqualToString:@"rewinding"])
553     {
554         [self sendAEWithEventClass:'hook' andEventID:'Paus'];
555         [self sendAEWithEventClass:'hook' andEventID:'Play'];
556     }
557     else
558     {
559         [self sendAEWithEventClass:'hook' andEventID:'Play'];
560         [playPauseMenuItem setTitle:@"Pause"];
561     }
562 }
563
564 - (void)nextSong:(id)sender
565 {
566     [self sendAEWithEventClass:'hook' andEventID:'Next'];
567 }
568
569 - (void)prevSong:(id)sender
570 {
571     [self sendAEWithEventClass:'hook' andEventID:'Prev'];
572 }
573
574 - (void)fastForward:(id)sender
575 {
576     [self sendAEWithEventClass:'hook' andEventID:'Fast'];
577 }
578
579 - (void)rewind:(id)sender
580 {
581     [self sendAEWithEventClass:'hook' andEventID:'Rwnd'];
582 }
583
584 - (void)quitMenuTunes:(id)sender
585 {
586     [NSApp terminate:self];
587 }
588
589 - (void)openiTunes:(id)sender
590 {
591     [[NSWorkspace sharedWorkspace] launchApplication:@"iTunes"];
592 }
593
594 - (void)showPreferences:(id)sender
595 {
596     if (!prefsController)
597     {
598         prefsController = [[PreferencesController alloc] initWithMenuTunes:self];
599         [self clearHotKeys];
600     }
601 }
602
603
604 - (void)closePreferences
605 {
606     if (!((iTunesPSN.highLongOfPSN == kNoProcess) && (iTunesPSN.lowLongOfPSN == 0)))
607     {
608         [self setupHotKeys];
609     }
610     [prefsController release];
611     prefsController = nil;
612 }
613
614 //
615 //
616 // Show Current Track Info And Show Upcoming Songs Floaters
617 //
618 //
619
620 - (void)showCurrentTrackInfo
621 {
622     NSString *trackName = [self runScriptAndReturnResult:@"return name of current track"];
623     if (!statusController && [trackName length])
624     {
625         NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
626         NSString *stringToShow = @"";
627         int lines = 1;
628         
629         if ([defaults boolForKey:@"showName"])
630         {
631             if ([defaults boolForKey:@"showArtist"])
632             {
633                 NSString *trackArtist = [self runScriptAndReturnResult:@"return artist of current track"];
634                 trackName = [NSString stringWithFormat:@"%@ - %@", trackArtist, trackName];
635             }
636             stringToShow = [stringToShow stringByAppendingString:trackName];
637             stringToShow = [stringToShow stringByAppendingString:@"\n"];
638             if ([trackName length] > 38)
639             {
640                 lines++;
641             }
642             lines++;
643         }
644         
645         if ([defaults boolForKey:@"showAlbum"])
646         {
647             NSString *trackAlbum = [self runScriptAndReturnResult:@"return album of current track"];
648             if ([trackAlbum length])
649             {
650                 stringToShow = [stringToShow stringByAppendingString:trackAlbum];
651                 stringToShow = [stringToShow stringByAppendingString:@"\n"];
652                 lines++;
653             }
654         }
655         
656         if ([defaults boolForKey:@"showTime"])
657         {
658             NSString *trackTime = [self runScriptAndReturnResult:@"return time of current track"];
659             if ([trackTime length])
660             {
661                 stringToShow = [NSString stringWithFormat:@"%@Total Time: %@\n", stringToShow, trackTime];
662                 lines++;
663             }
664         }
665         
666         {
667             int trackTimeLeft = [[self runScriptAndReturnResult:@"return (duration of current track) - player position"] intValue];
668             int minutes = trackTimeLeft / 60, seconds = trackTimeLeft % 60;
669             if (seconds < 10)
670             {
671                 stringToShow = [stringToShow stringByAppendingString:
672                             [NSString stringWithFormat:@"Time Remaining: %i:0%i", minutes, seconds]];
673             }
674             else
675             {
676                 stringToShow = [stringToShow stringByAppendingString:
677                             [NSString stringWithFormat:@"Time Remaining: %i:%i", minutes, seconds]];
678             }
679         }
680         
681         statusController = [[StatusWindowController alloc] init];
682         [statusController setTrackInfo:stringToShow lines:lines];
683         [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(fadeAndCloseStatusWindow) userInfo:nil repeats:NO];
684     }
685 }
686
687 - (void)showUpcomingSongs
688 {
689     if (!statusController)
690     {
691         int numSongs = [[self runScriptAndReturnResult:@"return number of tracks in current playlist"] intValue];
692         
693         if (numSongs > 0)
694         {
695             int numSongsInAdvance = [[NSUserDefaults standardUserDefaults] integerForKey:@"SongsInAdvance"];
696             int curTrack = [[self runScriptAndReturnResult:@"return index of current track"] intValue];
697             int i;
698             NSString *songs = @"";
699             
700             statusController = [[StatusWindowController alloc] init];
701             for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++)
702             {
703                 if (i <= numSongs)
704                 {
705                     NSString *curSong = [self runScriptAndReturnResult:[NSString stringWithFormat:@"return name of track %i of current playlist", i]];
706                     songs = [songs stringByAppendingString:curSong];
707                     songs = [songs stringByAppendingString:@"\n"];
708                 }
709             }
710             [statusController setUpcomingSongs:songs numSongs:numSongsInAdvance];
711             [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(fadeAndCloseStatusWindow) userInfo:nil repeats:NO];
712         }
713     }
714 }
715
716 - (void)fadeAndCloseStatusWindow
717 {
718     [statusController fadeWindowOut];
719     [statusController release];
720     statusController = nil;
721 }
722
723 @end