Added a chasing arrow icon to the Refresh item, removed the separator.
[MenuTunes.git] / MenuController.m
index 4898c09..0bc8c2d 100755 (executable)
@@ -8,6 +8,7 @@
 
 #import "MenuController.h"
 #import "MainController.h"
+#import "NetworkController.h"
 #import "ITMTRemote.h"
 #import <ITFoundation/ITDebug.h>
 #import <ITKit/ITHotKeyCenter.h>
@@ -21,7 +22,8 @@
 - (NSMenu *)playlistsMenu;
 - (NSMenu *)eqMenu;
 - (void)setKeyEquivalentForCode:(short)code andModifiers:(long)modifiers
-        onItem:(NSMenuItem *)item;
+        onItem:(id <NSMenuItem>)item;
+- (BOOL)iPodWithNameAutomaticallyUpdates:(NSString *)name;
 @end
 
 @implementation MenuController
     NSArray *menuArray = [defaults arrayForKey:@"menu"];
     NSEnumerator *enumerator = [menuArray objectEnumerator];
     NSString *nextObject;
-    NSMenuItem *tempItem;
+    id <NSMenuItem> tempItem;
     NSEnumerator *itemEnum;
     ITHotKey *hotKey;
     NSArray *hotKeys = [[ITHotKeyCenter sharedCenter] allHotKeys];
-    int currentSongRating;
+    ITMTRemote *mtr = [[MainController sharedController] currentRemote];
+    int currentSongRating = 0;
     
     //Get the information
     NS_DURING
-        _currentPlaylist = [[[MainController sharedController] currentRemote] currentPlaylistIndex];
-        _playingRadio = ([[[MainController sharedController] currentRemote] currentPlaylistClass] == ITMTRemotePlayerRadioPlaylist);
-        currentSongRating = ( [[[MainController sharedController] currentRemote] currentSongRating] != -1 );
+        _currentPlaylist = [mtr currentPlaylistIndex];
+        _playingRadio = ([mtr currentPlaylistClass] == ITMTRemotePlayerRadioPlaylist);
+        currentSongRating = ( [mtr currentSongRating] != -1 );
     NS_HANDLER
         [[MainController sharedController] networkError:localException];
     NS_ENDHANDLER
             
             ITDebugLog(@"Set \"Play\"/\"Pause\" menu item's title to correct state.");
             NS_DURING
-                switch ([[[MainController sharedController] currentRemote] playerPlayingState]) {
+                switch ([mtr playerPlayingState]) {
                     case ITMTRemotePlayerPlaying:
                         [tempItem setTitle:NSLocalizedString(@"pause", @"Pause")];
                     break;
             NS_DURING
                 tempItem = [menu addItemWithTitle:[NSString stringWithFormat:@"%@ %@",
                                 NSLocalizedString(@"show", @"Show"),
-                                    [[[MainController sharedController] currentRemote] playerSimpleName]]
+                                    [mtr playerSimpleName]]
                                 action:@selector(performMainMenuAction:)
                                 keyEquivalent:@""];
             NS_HANDLER
             ITDebugLog(@"Check to see if a Track is playing...");
             //Handle playing radio too
             if (_currentPlaylist) {
-                NSString *title;
+                NSString *title = nil;
                 NS_DURING
-                    title = [[[MainController sharedController] currentRemote] currentSongTitle];
+                    title = [mtr currentSongTitle];
                 NS_HANDLER
                     [[MainController sharedController] networkError:localException];
                 NS_ENDHANDLER
                 
                 if (!_playingRadio) {
                     if ([defaults boolForKey:@"showAlbum"]) {
-                        NSString *curAlbum;
+                        NSString *curAlbum = nil;
                         NS_DURING
-                            curAlbum = [[[MainController sharedController] currentRemote] currentSongAlbum];
+                            curAlbum = [mtr currentSongAlbum];
                         NS_HANDLER
                             [[MainController sharedController] networkError:localException];
                         NS_ENDHANDLER
                     }
                     
                     if ([defaults boolForKey:@"showArtist"]) {
-                        NSString *curArtist;
+                        NSString *curArtist = nil;
                         NS_DURING
-                            curArtist = [[[MainController sharedController] currentRemote] currentSongArtist];
+                            curArtist = [mtr currentSongArtist];
                         NS_HANDLER
                             [[MainController sharedController] networkError:localException];
                         NS_ENDHANDLER
                         }
                     }
                     
+                    if ([defaults boolForKey:@"showComposer"]) {
+                        NSString *curComposer = nil;
+                        NS_DURING
+                            curComposer = [mtr currentSongComposer];
+                        NS_HANDLER
+                            [[MainController sharedController] networkError:localException];
+                        NS_ENDHANDLER
+                        ITDebugLog(@"Add Track Composer (\"%@\") menu item.", curComposer);
+                        if ( curComposer ) {
+                            [menu indentItem:
+                                [menu addItemWithTitle:curComposer action:nil keyEquivalent:@""]];
+                        }
+                    }
+                    
                     if ([defaults boolForKey:@"showTrackNumber"]) {
-                        int track;
+                        int track = 0;
                         NS_DURING
-                            track = [[[MainController sharedController] currentRemote] currentSongTrack];
+                            track = [mtr currentSongTrack];
                         NS_HANDLER
                             [[MainController sharedController] networkError:localException];
                         NS_ENDHANDLER
                 }
                 
                 NS_DURING
-                    if ([defaults boolForKey:@"showTime"] && ( ([[[MainController sharedController] currentRemote] currentSongElapsed] != nil) || ([[[MainController sharedController] currentRemote] currentSongLength] != nil) )) {
-                        ITDebugLog(@"Add Track Elapsed (\"%@/%@\") menu item.", [[[MainController sharedController] currentRemote] currentSongElapsed], [[[MainController sharedController] currentRemote] currentSongLength]);
-                        [menu indentItem:[menu addItemWithTitle:[NSString stringWithFormat:@"%@/%@", [[[MainController sharedController] currentRemote] currentSongElapsed], [[[MainController sharedController] currentRemote] currentSongLength]] action:nil keyEquivalent:@""]];
+                    if ([defaults boolForKey:@"showTime"] && ( ([mtr currentSongElapsed] != nil) || ([mtr currentSongLength] != nil) )) {
+                        ITDebugLog(@"Add Track Elapsed (\"%@/%@\") menu item.", [mtr currentSongElapsed], [mtr currentSongLength]);
+                        [menu indentItem:[menu addItemWithTitle:[NSString stringWithFormat:@"%@/%@", [mtr currentSongElapsed], [mtr currentSongLength]] action:nil keyEquivalent:@""]];
                     }
                 NS_HANDLER
                     [[MainController sharedController] networkError:localException];
                 
                 if (!_playingRadio) {
                     NS_DURING
-                        if ([defaults boolForKey:@"showTrackRating"] && ( [[[MainController sharedController] currentRemote] currentSongRating] != -1.0 )) {
+                        if ([defaults boolForKey:@"showPlayCount"] && [mtr currentSource] == ITMTRemoteLibrarySource) {
+                            [menu indentItem:[menu addItemWithTitle:[NSString stringWithFormat:@"Play Count: %i", [mtr currentSongPlayCount]] action:nil keyEquivalent:@""]];
+                        }
+                        if ([defaults boolForKey:@"showTrackRating"] && ( [mtr currentSongRating] != -1.0 )) {
                             NSString *string = nil;
-                            switch ((int)([[[MainController sharedController] currentRemote] currentSongRating] * 5)) {
+                            switch ((int)([mtr currentSongRating] * 5)) {
                                 case 0:
                                     string = [NSString stringWithUTF8String:"☆☆☆☆☆"];
                                 break;
                     NS_HANDLER
                         [[MainController sharedController] networkError:localException];
                     NS_ENDHANDLER
+                    
+                    /*if ([tempItem respondsToSelector:@selector(setAttributedTitle:)] && [defaults boolForKey:@"showAlbumArtwork"] && ![[NetworkController sharedController] isConnectedToServer]) {
+                        NSImage *image = [mtr currentSongAlbumArt];
+                        if (image) {
+                            NSSize oldSize, newSize;
+                            oldSize = [image size];
+                            if (oldSize.width > oldSize.height) newSize = NSMakeSize(110,oldSize.height * (110.0f / oldSize.width));
+                            else newSize = NSMakeSize(oldSize.width * (110.0f / oldSize.height),110);
+                            image = [[[[NSImage alloc] initWithData:[image TIFFRepresentation]] autorelease] imageScaledSmoothlyToSize:newSize];
+                            
+                            tempItem = [menu addItemWithTitle:@"" action:nil keyEquivalent:@""];
+                            NSTextAttachment *attachment = [[[NSTextAttachment alloc] init] autorelease];
+                            [[attachment attachmentCell] setImage:image];
+                            NSAttributedString *attrString = [NSAttributedString attributedStringWithAttachment:attachment];
+                            [tempItem setAttributedTitle:attrString];
+                        }
+                    }*/
                 }
             } else {
                 ITDebugLog(@"No Track is Playing, Add \"No Song\" menu item.");
                 [tempItem setState:NSOffState];
             }
             NS_DURING
-                [[_eqMenu itemAtIndex:([[[MainController sharedController] currentRemote] currentEQPresetIndex] - 1)] setState:NSOnState];
+                [[_eqMenu itemAtIndex:0] setState:[mtr equalizerEnabled] ? NSOnState : NSOffState];
+                [[_eqMenu itemAtIndex:([mtr currentEQPresetIndex] + 1)] setState:NSOnState];
+                [[_eqMenu itemAtIndex:([mtr currentEQPresetIndex] - 1)] setState:NSOnState];
             NS_HANDLER
                 [[MainController sharedController] networkError:localException];
             NS_ENDHANDLER
                 }
                 
                 NS_DURING
-                    [[_ratingMenu itemAtIndex:([[[MainController sharedController] currentRemote] currentSongRating] * 5)] setState:NSOnState];
+                    [[_ratingMenu itemAtIndex:([mtr currentSongRating] * 5)] setState:NSOnState];
                 NS_HANDLER
                     [[MainController sharedController] networkError:localException];
                 NS_ENDHANDLER
 - (NSMenu *)menuForNoPlayer
 {
     NSMenu *menu = [[NSMenu alloc] initWithTitle:@""];
-    NSMenuItem *tempItem;
+    id <NSMenuItem> tempItem = nil;
     ITDebugLog(@"Creating menu for when player isn't running.");
     NS_DURING
         ITDebugLog(@"Add \"Open %@\" menu item.", [[[MainController sharedController] currentRemote] playerSimpleName]);
 - (void)rebuildSubmenus
 {
     ITDebugLog(@"Rebuilding all of the submenus.");
-    
     NS_DURING
         _currentPlaylist = [[[MainController sharedController] currentRemote] currentPlaylistIndex];
         _currentTrack = [[[MainController sharedController] currentRemote] currentSongIndex];
     NS_HANDLER
         [[MainController sharedController] networkError:localException];
     NS_ENDHANDLER
-    
+    ITDebugLog(@"Releasing old submenus.");
+    ITDebugLog(@" - Rating menu");
     [_ratingMenu release];
+    ITDebugLog(@" - Upcoming songs menu");
     [_upcomingSongsMenu release];
+    ITDebugLog(@" - Playlists menu");
     [_playlistsMenu release];
+    ITDebugLog(@" - EQ menu");
     [_eqMenu release];
     ITDebugLog(@"Beginning Rebuild of \"Song Rating\" submenu.");
     _ratingMenu = [self ratingMenu];
 - (NSMenu *)upcomingSongsMenu
 {
     NSMenu *upcomingSongsMenu = [[NSMenu alloc] initWithTitle:@""];
-    int numSongs, numSongsInAdvance = [[NSUserDefaults standardUserDefaults] integerForKey:@"SongsInAdvance"];
+    int numSongs = 0, numSongsInAdvance = [[NSUserDefaults standardUserDefaults] integerForKey:@"SongsInAdvance"];
     
     NS_DURING
         numSongs = [[[MainController sharedController] currentRemote] numberOfSongsInPlaylistAtIndex:_currentPlaylist];
     NS_ENDHANDLER
     
     ITDebugLog(@"Building \"Upcoming Songs\" menu.");
-    
     if (_currentPlaylist && !_playingRadio) {
         if (numSongs > 0) {
             int i;
-
             for (i = _currentTrack + 1; i <= _currentTrack + numSongsInAdvance; i++) {
                 if (i <= numSongs) {
-                    NSString *curSong;
+                    NSString *curSong = nil;
                     NS_DURING
                         curSong = [[[MainController sharedController] currentRemote] songTitleAtIndex:i];
                     NS_HANDLER
                         [[MainController sharedController] networkError:localException];
                     NS_ENDHANDLER
-                    NSMenuItem *songItem;
+                    id <NSMenuItem> songItem;
                     ITDebugLog(@"Adding song: %@", curSong);
                     songItem = [upcomingSongsMenu addItemWithTitle:curSong action:@selector(performUpcomingSongsMenuAction:) keyEquivalent:@""];
                     [songItem setTag:i];
                 }
             }
         }
+        
+        if ([upcomingSongsMenu numberOfItems] == 0) {
+            [upcomingSongsMenu addItemWithTitle:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.") action:NULL keyEquivalent:@""];
+        }
     }
     ITDebugLog(@"Done Building \"Upcoming Songs\" menu.");
     return upcomingSongsMenu;
 }
 
-- (NSMenu *)playlistsMenu
+/*- (NSMenu *)playlistsMenu
 {
     NSMenu *playlistsMenu = [[NSMenu alloc] initWithTitle:@""];
     NSArray *playlists;
-    NSMenuItem *tempItem;
+    id <NSMenuItem> tempItem;
+    ITMTRemotePlayerSource source = [[[MainController sharedController] currentRemote] currentSource];
     int i;
-    
     NS_DURING
         playlists = [[[MainController sharedController] currentRemote] playlists];
     NS_HANDLER
         [tempItem setTarget:self];
     }
     
-    if (!_playingRadio && _currentPlaylist) {
+    if (source == ITMTRemoteRadioSource) {
+        [[playlistsMenu addItemWithTitle:NSLocalizedString(@"radio", @"Radio") action:NULL keyEquivalent:@""] setState:NSOnState];
+    } else if (source == ITMTRemoteGenericDeviceSource) {
+        [[playlistsMenu addItemWithTitle:NSLocalizedString(@"genericDevice", @"Generic Device") action:NULL keyEquivalent:@""] setState:NSOnState];
+    } else if (source == ITMTRemoteiPodSource) {
+        [[playlistsMenu addItemWithTitle:NSLocalizedString(@"iPod", @"iPod") action:NULL keyEquivalent:@""] setState:NSOnState];
+    } else if (source == ITMTRemoteCDSource) {
+        [[playlistsMenu addItemWithTitle:NSLocalizedString(@"cd", @"CD") action:NULL keyEquivalent:@""] setState:NSOnState];
+    } else if (source == ITMTRemoteSharedLibrarySource) {
+        [[playlistsMenu addItemWithTitle:NSLocalizedString(@"sharedLibrary", @"Shared Library") action:NULL keyEquivalent:@""] setState:NSOnState];
+    } else if (source == ITMTRemoteLibrarySource && _currentPlaylist) {
+        [[playlistsMenu itemAtIndex:_currentPlaylist - 1] setState:NSOnState];
+    }
+    ITDebugLog(@"Done Building \"Playlists\" menu");
+    return playlistsMenu;
+}*/
+
+
+- (NSMenu *)playlistsMenu
+{
+    NSMenu *playlistsMenu = [[NSMenu alloc] initWithTitle:@""];
+    NSArray *playlists = nil;
+    id <NSMenuItem> tempItem;
+    ITMTRemotePlayerSource source = [[[MainController sharedController] currentRemote] currentSource];
+    int i, j;
+    NSMutableArray *indices = [[NSMutableArray alloc] init];
+    NS_DURING
+        playlists = [[[MainController sharedController] currentRemote] playlists];
+    NS_HANDLER
+        [[MainController sharedController] networkError:localException];
+    NS_ENDHANDLER
+    ITDebugLog(@"Building \"Playlists\" menu.");
+    {
+        NSArray *curPlaylist = [playlists objectAtIndex:0];
+        NSString *name = [curPlaylist objectAtIndex:0];
+        ITDebugLog(@"Adding main source: %@", name);
+        for (i = 3; i < [curPlaylist count]; i++) {
+            ITDebugLog(@"Adding playlist: %@", [curPlaylist objectAtIndex:i]);
+            tempItem = [playlistsMenu addItemWithTitle:[curPlaylist objectAtIndex:i] action:@selector(performPlaylistMenuAction:) keyEquivalent:@""];
+            [tempItem setTag:i - 1];
+            [tempItem setTarget:self];
+        }
+        ITDebugLog(@"Adding index to the index array.");
+        [indices addObject:[curPlaylist objectAtIndex:2]];
+    }
+    if ([playlists count] > 1) {
+        if ([[[playlists objectAtIndex:1] objectAtIndex:1] intValue] == ITMTRemoteRadioSource) {
+            [indices addObject:[[playlists objectAtIndex:1] objectAtIndex:2]];
+            if (source == ITMTRemoteRadioSource) {
+                [playlistsMenu addItem:[NSMenuItem separatorItem]];
+                [[playlistsMenu addItemWithTitle:NSLocalizedString(@"radio", @"Radio") action:@selector(performPlaylistMenuAction:) keyEquivalent:@""] setState:NSOnState];
+            }
+        } else {
+            [playlistsMenu addItem:[NSMenuItem separatorItem]];
+        }
+    }
+    
+    if ([playlists count] > 1) {
+        for (i = 1; i < [playlists count]; i++) {
+            NSArray *curPlaylist = [playlists objectAtIndex:i];
+            if ([[curPlaylist objectAtIndex:1] intValue] != ITMTRemoteRadioSource) {
+                NSString *name = [curPlaylist objectAtIndex:0];
+                NSMenu *submenu = [[NSMenu alloc] init];
+                ITDebugLog(@"Adding source: %@", name);
+                
+                if ( ([[curPlaylist objectAtIndex:1] intValue] == ITMTRemoteiPodSource) && [self iPodWithNameAutomaticallyUpdates:name] ) {
+                    ITDebugLog(@"Invalid iPod source.");
+                    [playlistsMenu addItemWithTitle:name action:NULL keyEquivalent:@""];
+                } else {
+                    for (j = 3; j < [curPlaylist count]; j++) {
+                        ITDebugLog(@"Adding playlist: %@", [curPlaylist objectAtIndex:j]);
+                        tempItem = [submenu addItemWithTitle:[curPlaylist objectAtIndex:j] action:@selector(performPlaylistMenuAction:) keyEquivalent:@""];
+                        [tempItem setTag:(i * 1000) + j - 1];
+                        [tempItem setTarget:self];
+                    }
+                    [[playlistsMenu addItemWithTitle:name action:NULL keyEquivalent:@""] setSubmenu:[submenu autorelease]];
+                }
+                ITDebugLog(@"Adding index to the index array.");
+                [indices addObject:[curPlaylist objectAtIndex:2]];
+            }
+        }
+    }
+    ITDebugLog(@"Checking the current source.");
+    if ( (source == ITMTRemoteSharedLibrarySource) || (source == ITMTRemoteiPodSource) || (source == ITMTRemoteGenericDeviceSource) || (source == ITMTRemoteCDSource) ) {
+        tempItem = [playlistsMenu itemAtIndex:[playlistsMenu numberOfItems] + [indices indexOfObject:[NSNumber numberWithInt:[[[MainController sharedController] currentRemote] currentSourceIndex]]] - [indices count]];
+        [tempItem setState:NSOnState];
+        [[[tempItem submenu] itemAtIndex:_currentPlaylist - 1] setState:NSOnState];
+    } else if (source == ITMTRemoteLibrarySource && _currentPlaylist) {
         [[playlistsMenu itemAtIndex:_currentPlaylist - 1] setState:NSOnState];
     }
+    [indices release];
+    tempItem = [playlistsMenu addItemWithTitle:NSLocalizedString(@"refresh", @"Refresh") action:@selector(rebuildSubmenus) keyEquivalent:@""];
+    [tempItem setTarget:self];
+    [tempItem setImage:[NSImage imageNamed:@"ChasingArrow"]];
     ITDebugLog(@"Done Building \"Playlists\" menu");
     return playlistsMenu;
 }
 - (NSMenu *)eqMenu
 {
     NSMenu *eqMenu = [[NSMenu alloc] initWithTitle:@""];
-    NSArray *eqPresets;
-    NSMenuItem *tempItem;
+    NSArray *eqPresets = nil;
+    id <NSMenuItem> tempItem;
     int i;
     
     NS_DURING
     
     ITDebugLog(@"Building \"EQ Presets\" menu.");
     
+    tempItem = [eqMenu addItemWithTitle:@"Enabled" action:@selector(performEqualizerMenuAction:) keyEquivalent:@""];
+    [tempItem setTag:-1];
+    [tempItem setTarget:self];
+    NS_DURING
+        [tempItem setState:[[[MainController sharedController] currentRemote] equalizerEnabled] ? NSOnState : NSOffState];
+    NS_HANDLER
+        [[MainController sharedController] networkError:localException];
+    NS_ENDHANDLER
+    [eqMenu addItem:[NSMenuItem separatorItem]];
+    
     for (i = 0; i < [eqPresets count]; i++) {
         NSString *name;
           if ( ( name = [eqPresets objectAtIndex:i] ) ) {
 }
 
 - (void)setKeyEquivalentForCode:(short)code andModifiers:(long)modifiers
-        onItem:(NSMenuItem *)item
+        onItem:(id <NSMenuItem>)item
 {
     unichar charcode = 'a';
     int i;
     ITDebugLog(@"Done setting key equivalent on menu item: %@", [item title]);
 }
 
+- (BOOL)iPodWithNameAutomaticallyUpdates:(NSString *)name
+{
+    NSArray *volumes = [[NSWorkspace sharedWorkspace] mountedLocalVolumePaths];
+    NSEnumerator *volEnum = [volumes objectEnumerator];
+    NSString *nextVolume;
+    ITDebugLog(@"Looking for an iPod named %@", name);
+    while ( (nextVolume = [volEnum nextObject]) ) {
+        ITDebugLog(@"- %@", nextVolume);
+        if ([nextVolume rangeOfString:name options:nil /*range:NSMakeRange(0, [name length] - 1)*/].location != NSNotFound) {
+            NSFileHandle *handle;
+            NSData *data;
+            NSString *path = [nextVolume stringByAppendingPathComponent:@"/iPod_Control/iTunes/iTunesPrefs"];
+            if ( ![[NSFileManager defaultManager] fileExistsAtPath:path] ) {
+                ITDebugLog(@"Error, path isn't an iPod! %@", path);
+                return NO;
+            }
+            handle = [NSFileHandle fileHandleForReadingAtPath:path];
+            ITDebugLog(@"File handle: %@", handle);
+            [handle seekToFileOffset:10];
+            data = [handle readDataOfLength:1];
+            ITDebugLog(@"Data: %@", data);
+            if ( (*((unsigned char*)[data bytes]) == 0x00) ) {
+                ITDebugLog(@"iPod is manually updated. %@", path);
+                return NO;
+            } else if ( ( *((unsigned char*)[data bytes]) == 0x01 ) ) {
+                ITDebugLog(@"iPod is automatically updated. %@", path);
+                return YES;
+            } else {
+                ITDebugLog(@"Error! Value: %h  Desc: %@ Path: %@", *((unsigned char*)[data bytes]), [data description], path);
+                return NO;
+            }
+        }
+    }
+    return YES;
+}
+
 @end
\ No newline at end of file