~juri/nowplayingsaver/trunk

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
//
//  NowPlayingSaverView.m
//  NowPlayingSaver
//
//  Created by Juri Pakaste on 13.9.09.
//  Copyright (c) 2009, Juri Pakaste. All rights reserved.
//  For licensing details see the file COPYING.
//

#import "NowPlayingSaverView.h"

#import "ArtworkAnimator.h"
#import "ArtworkBlowFadeAnimator.h"
#import "ArtworkCircleAnimator.h"
#import "ArtworkDoorwayAnimator.h"
#import "ArtworkFadeOutInAnimator.h"
#import "ArtworkFlipAnimator.h"
#import "ArtworkFromSideAnimator.h"
#import "ArtworkDrillAnimator.h"
#import "ArtworkScaleDownUpAnimator.h"
#import "ElementProvider.h"
#import "iTunes.h"
#import "NPSProgressIndicator.h"

#import <dispatch/dispatch.h>



@implementation NowPlayingInfo

-(NSString*)description
{
    return [NSString stringWithFormat:@"<%@ trackName:%@ trackNumber:%d albumName:%@ artistName:%@ albumArtistName:%@ dbId:%d>", self.class, self.trackName, self.trackNumber, self.albumName, self.artistName, self.albumArtistName, self.dbId];
}

@synthesize trackName;
@synthesize trackNumber;
@synthesize albumName;
@synthesize artistName;
@synthesize albumArtistName;
@synthesize dbId;
@synthesize artwork;
@synthesize duration;
@synthesize position;

@end



#pragma mark -


@interface NowPlayingSaverView ()

-(NSString*)formatTrackInfo:(NowPlayingInfo*)info;
-(void)callITunes;
-(void)newTrackStarted:(NowPlayingInfo*)info;
-(void)iTunesNotRunning;
-(void)iTunesNotPlaying;
-(void)playingSameTrackAtPosition:(NSInteger)position ofDuration:(NSInteger)duration;
-(void)animateArtworkTransitionToImage:(NSImage*)image;


@property (retain, nonatomic) NowPlayingInfo* nowPlayingInfo;
@property (retain, nonatomic) NSImage* defaultImage;
@property (retain, nonatomic) iTunesApplication* player;

@end


@implementation NowPlayingSaverView

static inline BOOL empty(NSString* s)
{
    return (s == nil) || ([s length] == 0);
}

-(NSString*)formatTrackInfo:(NowPlayingInfo*)info
{
    NSMutableString* infoString = [[NSMutableString alloc] init];
    if (! empty(info.albumName))
    {
        if (! empty(info.albumArtistName))
            [infoString appendFormat:@"%@: ", info.albumArtistName];
        else if (! empty(info.artistName))
            [infoString appendFormat:@"%@: ", info.artistName];
            
        [infoString appendFormat:@"%@\n", info.albumName];
        
        if ((! [info.artistName isEqualToString:info.albumArtistName]) &&
            (! empty(info.albumArtistName)) &&
            (! empty(info.artistName)))
            [infoString appendFormat:@"%@: ", info.artistName];
    }
    else
    {
        if (! empty(info.artistName))
            [infoString appendFormat:@"%@: ", info.artistName];
    }

    [infoString appendFormat:@"%d - %@", info.trackNumber, ((info.trackName != nil) ? info.trackName : @"(no name)")];
    
    return infoString;
}


-(void)animateArtworkTransitionToImage:(NSImage*)image
{
    ArtworkAnimator* animator = [self.elementProvider element];
    [animator animateArtworkLayer:self.albumArtView.layer toArtwork:image];
}


-(void)newTrackStarted:(NowPlayingInfo*)info
{
    self.nowPlayingInfo = info;
    [self.albumInfoView setStringValue:[self formatTrackInfo:info]];
    NSImage* img = info.artwork != nil ? info.artwork : self.defaultImage;
//    [self.albumArtView setImage:img];
    [self animateArtworkTransitionToImage:img];
    [self.progressIndicator setValue:(info.position) / info.duration];
    [self setNeedsDisplay:YES];
}


-(void)iTunesNotRunning
{
    self.nowPlayingInfo = nil;
    [self.albumInfoView setStringValue:@"iTunes is not running"];
    [self.albumArtView setImage:nil];
    [self.progressIndicator setValue:0];
}


-(void)iTunesNotPlaying
{
    self.nowPlayingInfo = nil;
    [self.albumInfoView setStringValue:@"iTunes is playing nothing"];
    [self.albumArtView setImage:nil];
    [self.progressIndicator setValue:0];
}


-(void)playingSameTrackAtPosition:(NSInteger)position ofDuration:(NSInteger)duration
{
    [self.progressIndicator setValue:(double)position / duration animated:YES];
}


#define NOWS(s) [s stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]

-(void)callITunes
{
    NSInteger currentDbId = (self.nowPlayingInfo != nil) ? self.nowPlayingInfo.dbId : -1;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        iTunesApplication* iTunes = self.player;
        NowPlayingInfo* info = [[NowPlayingInfo alloc] init];

        if (! [iTunes isRunning])
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self iTunesNotRunning];
            });
            return;
        }
                
        iTunesTrack* currentTrack = iTunes.currentTrack;
        
        if (! [currentTrack exists])
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self iTunesNotPlaying];
            });
            return;
        }
        
        NSInteger newId = currentTrack.databaseID;
        if (newId == currentDbId)
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self playingSameTrackAtPosition:iTunes.playerPosition ofDuration:currentTrack.duration]; 
            });
            return;
        }
        
        info.trackName = NOWS(currentTrack.name);
        info.trackNumber = currentTrack.trackNumber;
        info.artistName = NOWS(currentTrack.artist);
        info.albumName = NOWS(currentTrack.album);
        info.albumArtistName = NOWS(currentTrack.albumArtist);
        info.dbId = newId;
        info.duration = currentTrack.duration;
        info.position = iTunes.playerPosition;
        // TODO: which artwork should we pick and is this the best way
        NSArray* artworks = currentTrack.artworks;
        iTunesArtwork* artwork = ((artworks != nil) && [artworks count]) ? [artworks objectAtIndex:0] : nil;
        info.artwork = artwork != nil ? artwork.data : nil;

        dispatch_async(dispatch_get_main_queue(), ^{
            [self newTrackStarted:info]; 
        });
        
    });
}

- (id)initWithFrame:(NSRect)frame isPreview:(BOOL)isPreview
{
    if ((self = [super initWithFrame:frame isPreview:isPreview]))
    {
        [self setAnimationTimeInterval:0];
        self.nowPlayingInfo = nil;
        if (! [NSBundle loadNibNamed:@"iTunesDataView" owner:self])
        {
            NSLog(@"NowPlayingSaver nib loading failed");
        }
        [self addSubview:self.infoFrame];

        CALayer* layer = [CALayer layer];
        self.albumArtView.layer = layer;
        self.albumArtView.wantsLayer = YES;
        layer.bounds = self.albumArtView.bounds;
        layer.contentsGravity = kCAGravityResizeAspect;
        layer.anchorPoint = CGPointMake(0.5, 0.5);
        
        self.infoFrame.frame = self.bounds;
        NSString* itunesPath = [[NSWorkspace sharedWorkspace] fullPathForApplication:@"iTunes"];
        self.defaultImage = [[NSImage alloc] initByReferencingFile:[[NSBundle bundleWithPath:itunesPath] pathForResource:@"iTunes" ofType:@"icns"]];
        self.elementProvider = [[RandomElementProvider alloc] 
                                initWithElements:
                                [NSArray arrayWithObjects:
                                 [[ArtworkFadeOutInAnimator alloc] init],
                                 [[ArtworkScaleDownUpAnimator alloc] init],
                                 [[ArtworkDrillAnimator alloc] init],
                                 [[ArtworkFlipAnimator alloc] initWithAxis:kArtworkFlipAxisX],
                                 [[ArtworkFlipAnimator alloc] initWithAxis:kArtworkFlipAxisY],
                                 [[ArtworkFromSideAnimator alloc] initWithDirection:kArtworkFromSideLeft],
                                 [[ArtworkFromSideAnimator alloc] initWithDirection:kArtworkFromSideRight],
                                 [[ArtworkCircleAnimator alloc] initWithDirection:kArtworkCircleClockwise],
                                 [[ArtworkCircleAnimator alloc] initWithDirection:kArtworkCircleCounterClockwise],
                                 [[ArtworkDoorwayAnimator alloc] init],
                                 [[ArtworkBlowFadeAnimator alloc] init],
                                 nil]];
        srandomdev();
    }
    return self;
}

-(void)showFakeInfo:(NowPlayingInfo*)info
{
    [self newTrackStarted:info];
}

- (void)startAnimation
{
    [super startAnimation];
    self.player = [SBApplication applicationWithBundleIdentifier:@"com.apple.iTunes"];
    self.progressIndicator.color = [self.albumInfoView textColor];

}

- (void)stopAnimation
{
    [super stopAnimation];
}

- (void)drawRect:(NSRect)rect
{
    [super drawRect:rect];
}

-(NSTimeInterval)animationTimeInterval
{
    return 2;
}

- (void)animateOneFrame
{
    [self callITunes];
}

- (BOOL)hasConfigureSheet
{
    return NO;
}

- (NSWindow*)configureSheet
{
    return nil;
}

@synthesize albumArtView;
@synthesize albumInfoView;
@synthesize defaultImage;
@synthesize elementProvider;
@synthesize infoFrame;
@synthesize nowPlayingInfo;
@synthesize player;
@synthesize progressIndicator;

@end