forked from robbiehanson/AlarmClock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAlarmController.m
1093 lines (934 loc) · 30 KB
/
AlarmController.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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#import "AlarmController.h"
#import "Alarm.h"
#import "AlarmScheduler.h"
#import "Prefs.h"
#import "ITunesData.h"
#import "ITunesPlayer.h"
#import "MTCoreAudioDevice.h"
#import "AppleRemote.h"
// Declare private methods
@interface AlarmController (PrivateAPI)
- (void)parseITunesMusicLibrary;
- (void)setupPlayer;
- (void)playerPlay;
- (void)playerStop;
- (void)playerNextTrack;
- (void)playerPreviousTrack;
- (void)snooze;
- (void)stop;
- (void)setVolume:(float)percent;
- (void)runAppleScript:(NSObject *)obj;
@end
@implementation AlarmController
// INIT, DEALLOC
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/* Initializes object with proper nib */
- (id)init
{
if(self = [super initWithWindowNibName:@"AlarmWindow"])
{
// Get the alarm that is supposed to go off
lastAlarm = [[AlarmScheduler lastAlarmClone] retain];
// Get preferences
anyKeyStops = [Prefs anyKeyStops];
isDigitalAudio = [Prefs digitalAudio];
easyWakeDuration = [Prefs easyWakeDuration] * 60;
snoozeDuration = [Prefs snoozeDuration] * 60;
killDuration = [Prefs killDuration] * 60;
prefVolume = [Prefs prefVolume];
minVolume = [Prefs minVolume];
maxVolume = [Prefs maxVolume];
// Initialize time formatter
timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[timeFormatter setDateStyle:NSDateFormatterNoStyle];
[timeFormatter setTimeStyle:NSDateFormatterMediumStyle];
// Intialize the alarm status variables
alarmStatus = STATUS_ACTIVE;
isDataReady = NO;
isPlayerReady = NO;
// Initialize status line variables
statusOffset = 0;
shouldDisplaySongInfo = YES;
// Initialize localized strings
anyKeyStopStr = [NSLocalizedStringFromTable(@"Press Any key to stop", @"AlarmWindow", @"Status line above clock during alarm") retain];
enterKeySnoozeStr = [NSLocalizedStringFromTable(@"Press Enter to snooze", @"AlarmWindow", @"Status line above clock during alarm") retain];
anyKeySnoozeStr = [NSLocalizedStringFromTable(@"Press Any key to snooze", @"AlarmWindow", @"Status line above clock during alarm") retain];
enterKeyStopStr = [NSLocalizedStringFromTable(@"Press Enter to stop", @"AlarmWindow", @"Status line above clock during alarm") retain];
snoozingTilStr = [NSLocalizedStringFromTable(@"Snoozing until", @"AlarmWindow", @"Status line above clock during snooze") retain];
alarmStartStr = [NSLocalizedStringFromTable(@"Starting alarm...", @"AlarmWindow", @"Status line above clock when first starting alarm") retain];
alarmKillStr = [NSLocalizedStringFromTable(@"Alarm terminated!", @"AlarmWindow", @"Status line above clock after alarm is stopped") retain];
snoozeStr = [NSLocalizedStringFromTable(@"Snooze", @"AlarmWindow", @"Button below clock") retain];
stopStr = [NSLocalizedStringFromTable(@"Stop", @"AlarmWindow", @"Button below clock") retain];
timeStr = [[timeFormatter stringFromDate:[NSDate date]] retain];
// Initialize core audio device for changing system volume
outputDevice = [[MTCoreAudioDevice defaultOutputDevice] retain];
// Store the initial system volume
// These get restored after the alarm is stopped
initialLeftVolume = [outputDevice volumeForChannel:1 forDirection:kMTCoreAudioDevicePlaybackDirection];
initialRightVolume = [outputDevice volumeForChannel:2 forDirection:kMTCoreAudioDevicePlaybackDirection];
// Configure the volume
// The setVolume method automatically takes care of unmuting the volume
if([lastAlarm usesEasyWake])
[self setVolume:minVolume];
else
[self setVolume:prefVolume];
// Initialize lock
lock = [[NSLock alloc] init];
}
return self;
}
/**
Called after laoding the nib file
Configures gui elements
**/
- (void)awakeFromNib
{
// Record the starting time
startTime = [[lastAlarm time] retain];
// Start the timer
timer = [[NSTimer scheduledTimerWithTimeInterval:0.5
target:self
selector:@selector(updateAndCheck:)
userInfo:nil
repeats:YES] retain];
// Initially set it's time
[roundedView setNeedsDisplay:YES];
// Center the window
// Don't forget to turn of cascading, or the windows will continually cascade
[self setShouldCascadeWindows:NO];
[[self window] center];
}
- (void)dealloc
{
NSLog(@"Destroying %@", self);
// Release last alarm
[lastAlarm release];
// Release timer
[timer release];
// Release iTunes Data and Player, and core audio device
[data release];
[player release];
[outputDevice release];
// Release startTime
[startTime release];
// Release formatter used to display current time
[timeFormatter release];
// Release lock
[lock release];
// Release localized strings
[anyKeyStopStr release];
[enterKeySnoozeStr release];
[anyKeySnoozeStr release];
[enterKeyStopStr release];
[snoozingTilStr release];
[alarmStartStr release];
[alarmKillStr release];
[snoozeStr release];
[stopStr release];
[timeStr release];
// Move up the inheritance chain
[super dealloc];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Window Delegate Methods
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
Sent after the window owned by the receiver has been loaded.
**/
- (void)windowDidLoad
{
// Start parsing iTunes Music Library in background thread
[NSThread detachNewThreadSelector:@selector(parseThread:) toTarget:self withObject:nil];
// Turn off the screen saver
[NSThread detachNewThreadSelector:@selector(runAppleScript:) toTarget:self withObject:nil];
// Note that Cocoa's thread management system retains the target during the execution of the detached thread
// When the thread terminates, the target gets released
// Thus, since self will be retained, dealloc won't be called until these threads are completed
// Bring application, and window to the front
[[self window] makeKeyAndOrderFront:self];
[NSApp activateIgnoringOtherApps:YES];
}
/**
Called when the window is about to close.
In this case, it's after the user has stopped the alarm, and the window has faded out.
**/
- (void)windowWillClose:(NSNotification *)aNotification
{
// Stop the timer
// It would still be running if the user quit the app with this window still open
[timer invalidate];
// Post notification for stopped alarm
// This informs the WindowManager to remove the alarm from it's list of active alarm windows
[[NSNotificationCenter defaultCenter] postNotificationName:@"AlarmClosed" object:self];
// Release self
[self autorelease];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Parsing iTunes and Playing Alarm
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
Background thread function to parse iTunes library.
This method is run in a separate thread, allowing the GUI to remain responsive.
**/
- (void)parseThread:(NSObject *)obj
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[self parseITunesMusicLibrary];
[pool release];
}
/**
Parses the iTunes data into memory.
Invokes the proper procedures to parse the iTunes music library into memory.
After this is complete, the alarm informations is validated with the fresh iTunes information.
This method is muli-thread safe (the method first requests a lock).
**/
- (void)parseITunesMusicLibrary
{
[lock lock];
// Parse iTunes data if needed
if(!isDataReady)
{
NSLog(@"Parsing iTunes Music Library...");
NSDate *start = [NSDate date];
// Parse the iTunes Music Library
data = [[ITunesData alloc] init];
// The stored trackID may have changed
// Check this, and update the alarm if needed
int correctTrackID = [data validateTrackID:[lastAlarm trackID]
withPersistentTrackID:[lastAlarm persistentTrackID]];
if(correctTrackID != [lastAlarm trackID])
{
[lastAlarm setTrackID:correctTrackID withPersistentTrackID:[lastAlarm persistentTrackID]];
}
// The stored playlistID may have changed
// Check this, and update the alarm if needed
int correctPlaylistID = [data validatePlaylistID:[lastAlarm playlistID]
withPersistentPlaylistID:[lastAlarm persistentPlaylistID]];
if(correctPlaylistID != [lastAlarm playlistID])
{
[lastAlarm setPlaylistID:correctPlaylistID withPersistentPlaylistID:[lastAlarm persistentPlaylistID]];
}
NSDate *end = [NSDate date];
NSLog(@"Done parsing (time: %f seconds)", [end timeIntervalSinceDate:start]);
// Update the data status
// This lets the other methods know it's now safe to initialize the player
isDataReady = YES;
}
[lock unlock];
}
/**
This method initializes and configures the ITunesPlayer.
Because the ITunesPlayer initializes a QTMovie, and QTMovie objects must be initialized in the main thread,
the player must also be initialized in the main thread.
This method should be called after the data is ready.
This method is muli-thread safe (the method first requests a lock).
**/
- (void)setupPlayer
{
// We can't do anything if we don't have the ITunesData yet
if(!isDataReady) return;
[lock lock];
if(!isPlayerReady)
{
// Initialize ITunesPlayer
player = [[ITunesPlayer alloc] initWithITunesData:data];
// Configure self as delegate - we will implement iTunesPlayerChangedSong method
[player setDelegate:self];
// Set the alarm
if([lastAlarm isPlaylist])
{
// Using a playlist
NSLog(@"Setting alarm with playlistID: %i", [lastAlarm playlistID]);
[player setPlaylistWithPlaylistID:[lastAlarm playlistID] usesShuffle:[lastAlarm usesShuffle]];
}
else if([lastAlarm isTrack])
{
// Using a single track
NSLog(@"Setting alarm with trackID: %i", [lastAlarm trackID]);
[player setTrackWithTrackID:[lastAlarm trackID]];
}
else
{
// No alarm file set, use default alarm file
NSLog(@"Setting alarm with defaultAlarmFile");
[player setFileWithPath:[Alarm defaultAlarmFile]];
}
// Update the player status
// This lets the other methods know it's now safe to interact with the player
isPlayerReady = YES;
}
[lock unlock];
}
/**
This method starts the player, and verifies it's playing properly.
If anything goes wrong, it reverts to the default alarm file.
**/
- (void)playerPlay
{
if(isDataReady && isPlayerReady)
{
// Start the alarm
[player play];
// Check to make sure the alarm is playing
// If it's not, then play the default alarm file
if(![player isPlaying])
{
NSLog(@"Alarm failed to play! Reverting to defaultAlarmFile!");
[player setFileWithPath:[Alarm defaultAlarmFile]];
[player play];
}
}
}
/**
This method stops the player from playing.
**/
- (void)playerStop
{
if(isDataReady && isPlayerReady)
{
[player stop];
}
}
/**
This method moves the player to the next track
**/
- (void)playerNextTrack
{
if(isDataReady && isPlayerReady)
{
if([player isPlaylist])
{
// Move to the next track
[player nextTrack];
// Force the display of song info
statusOffset = (int)[[NSDate date] timeIntervalSinceDate:startTime];
shouldDisplaySongInfo = YES;
}
}
}
/**
This method moves the player to the previous track
**/
- (void)playerPreviousTrack
{
if(isDataReady && isPlayerReady)
{
if([player isPlaylist])
{
// Move to the previous track
[player previousTrack];
// Force the display of song info
statusOffset = (int)[[NSDate date] timeIntervalSinceDate:startTime];
shouldDisplaySongInfo = YES;
}
}
}
/**
Called by ITunesPlayer when the song changes.
This lets us know we should force the display of song info
**/
- (void)iTunesPlayerChangedSong
{
NSLog(@"iTunesPlayerChangedSong");
statusOffset = (int)[[NSDate date] timeIntervalSinceDate:startTime];
shouldDisplaySongInfo = YES;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Correspondence Info Methods
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (BOOL)shouldDisplayPlusMinusButtons
{
if(alarmStatus == STATUS_SNOOZING)
{
return YES;
}
else if(alarmStatus == STATUS_ACTIVE)
{
return [player isPlaylist];
}
else
{
return NO;
}
}
- (NSString *)statusLine1
{
if(alarmStatus == STATUS_ACTIVE)
{
if([[NSDate date] timeIntervalSinceDate:startTime] < 3.0)
{
// Less than 3 seconds have elapsed since the alarm became active
// At this point we're still ignoring keyboard input, so we display the starting message
return alarmStartStr;
}
else if(!isPlayerReady)
{
// At least 3 seconds have elapsed since the alarm became active
// But the player isn't ready yet, so instead of displaying empty strings
// we're going to simply force display of the keyboard information
if(anyKeyStops)
return anyKeyStopStr;
else
return anyKeySnoozeStr;
}
else
{
// We either need to display the song info or the keyboard info
// We switch back and forth between the 2 every 10 seconds
// We also allow the user to manually switch between the 2 views
if(shouldDisplaySongInfo)
{
return [[player currentTrack] objectForKey:@"Name"];
}
else
{
if(anyKeyStops)
return anyKeyStopStr;
else
return anyKeySnoozeStr;
}
}
}
else if(alarmStatus == STATUS_SNOOZING)
{
return snoozingTilStr;
}
else
{
return alarmKillStr;
}
}
- (NSString *)statusLine2
{
if(alarmStatus == STATUS_ACTIVE)
{
if([[NSDate date] timeIntervalSinceDate:startTime] < 3.0)
{
// Less than 3 seconds have elapsed since the alarm became active
// At this point we're still ignoring keyboard input, so we display the starting message
return @"";
}
else if(!isPlayerReady)
{
// At least 3 seconds have elapsed since the alarm became active
// But the player isn't ready yet, so instead of displaying empty strings
// we're going to simply force display of the keyboard information
if(anyKeyStops)
return enterKeySnoozeStr;
else
return enterKeyStopStr;
}
else
{
// We either need to display the song info or the keyboard info
// We switch back and forth between the 2 every 10 seconds
// We also allow the user to manually switch between the 2 views
if(shouldDisplaySongInfo)
{
return [[player currentTrack] objectForKey:@"Artist"];
}
else
{
if(anyKeyStops)
return enterKeySnoozeStr;
else
return enterKeyStopStr;
}
}
}
else if(alarmStatus == STATUS_SNOOZING)
{
return [timeFormatter stringFromDate:startTime];
}
else
{
return @"";
}
}
/**
Returns the string to be displayed in the button traditionally used for increasing the snooze duration.
**/
- (NSString *)plusButtonStr
{
if(alarmStatus == STATUS_ACTIVE)
return @">";
else if(alarmStatus == STATUS_SNOOZING)
return @"+";
else
return @"";
}
/**
Returns the string to be displayed in the button traditionally used for decreasing the snooze duration.
**/
- (NSString *)minusButtonStr
{
if(alarmStatus == STATUS_ACTIVE)
return @"<";
else if(alarmStatus == STATUS_SNOOZING)
return @"-";
else
return @"";
}
- (NSString *)timeStr
{
// Wondering why we're using a timeStr, and not just formatting the current date every time this method is called?
// It's because:
// We don't want to update the time after the alarm is terminated!!!
// If we format the current time right here, the time gets updated after the alarm is terminated,
// while the user is interacting with the Alarm Window UI. Which looks really odd!
return timeStr;
}
- (NSString *)leftButtonStr
{
return snoozeStr;
}
- (NSString *)rightButtonStr
{
return stopStr;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Correspondence Action Methods
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)statusLineClicked
{
// We want to switch between displaying song info and keyboard info
statusOffset = (int)[[NSDate date] timeIntervalSinceDate:startTime];
shouldDisplaySongInfo = !shouldDisplaySongInfo;
}
/**
Plus button clicked by user.
We increase the snooze duration by 1 minute.
**/
- (void)plusButtonClicked
{
if(alarmStatus == STATUS_SNOOZING)
{
NSCalendarDate *newStartTime;
if([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask)
newStartTime = [startTime dateByAddingYears:0 months:0 days:0 hours:0 minutes:5 seconds:0];
else
newStartTime = [startTime dateByAddingYears:0 months:0 days:0 hours:0 minutes:1 seconds:0];
[startTime release];
startTime = [newStartTime retain];
NSLog(@"Increasing Snooze: %@", startTime);
}
else if(alarmStatus == STATUS_ACTIVE)
{
[self playerNextTrack];
}
}
/**
Minus button clicked by user.
We decrease the snooze duration by 1 minute. (If this won't make the alarm immediately go off)
**/
- (void)minusButtonClicked
{
if(alarmStatus == STATUS_SNOOZING)
{
NSCalendarDate *newStartTime;
if([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask)
newStartTime = [startTime dateByAddingYears:0 months:0 days:0 hours:0 minutes:-5 seconds:0];
else
newStartTime = [startTime dateByAddingYears:0 months:0 days:0 hours:0 minutes:-1 seconds:0];
if([newStartTime timeIntervalSinceNow] > 0)
{
[startTime release];
startTime = [newStartTime retain];
NSLog(@"Decreasing Snooze: %@", startTime);
}
}
else if(alarmStatus == STATUS_ACTIVE)
{
[self playerPreviousTrack];
}
}
/**
Snooze button clicked by user
**/
- (void)leftButtonClicked
{
[self snooze];
}
/**
Stop button clicked by user
**/
- (void)rightButtonClicked
{
[self stop];
}
/**
Called to determine if the system should be allowed to sleep.
This is fine if the alarm is terminated or stopped.
Otherwise, we would prefer that it didn't.
**/
- (BOOL)canSystemSleep
{
return ((alarmStatus == STATUS_TERMINATED) || (alarmStatus == STATUS_STOPPED));
}
/**
Called prior to the system going to sleep.
We need to return the time at which this alarm will stop snoozing.
**/
- (NSCalendarDate *)systemWillSleep
{
// Call snooze method
// If the alarm is active, this will obviously snooze it
// Otherwise it will have absolutely no effect.
[self snooze];
// Now, if the alarm was active, it's now snoozing
// And if it was snoozing, well then it's still snoozing now isn't it
if(alarmStatus == STATUS_SNOOZING)
return [[startTime copy] autorelease];
else
return nil;
}
/**
Called after the system has woken from sleep.
**/
- (void)systemDidWake
{
// We don't actually have anything to do here.
// The timer is still active, and will take care of setting off the alarm if needed.
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark General Correspondence
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (int)alarmStatus
{
return alarmStatus;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Action Methods
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)snooze
{
if(alarmStatus == STATUS_ACTIVE)
{
// Update the alarm status
alarmStatus = STATUS_SNOOZING;
// Stop playing the music
[self playerStop];
// Automatically go to the next song (is using a playlist)
[self playerNextTrack];
// Reset the snooze time
NSCalendarDate *now = [NSCalendarDate calendarDate];
[startTime release];
startTime = [[now dateByAddingYears:0 months:0 days:0 hours:0 minutes:0 seconds:snoozeDuration] retain];
NSLog(@"Snoozing til: %@", startTime);
// Set window so it can be put in the background
[[self window] setLevel: NSNormalWindowLevel];
// Reset the volume if using easy wake
// This way you don't hear "You've Got Mail" really loud while you're snoozing
if([lastAlarm usesEasyWake])
{
[self setVolume:minVolume];
}
}
}
- (void)stop
{
if(alarmStatus != STATUS_STOPPED)
{
NSLog(@"Stopping alarm...");
// Update the alarm status
alarmStatus = STATUS_STOPPED;
// Stop playing the music
[self playerStop];
// Stop the timer
[timer invalidate];
// Start a timer to fade out the window
// After the fade is complete, the window will automatically be closed
[NSTimer scheduledTimerWithTimeInterval:0.05
target:roundedView
selector:@selector(fade:)
userInfo:nil
repeats:NO];
// Return the system volume to it's original level (before the alarm went off)
[outputDevice setVolume:initialLeftVolume forChannel:1 forDirection:kMTCoreAudioDevicePlaybackDirection];
[outputDevice setVolume:initialRightVolume forChannel:2 forDirection:kMTCoreAudioDevicePlaybackDirection];
}
}
// Timer Events
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)updateAndCheck:(NSTimer *)aTimer
{
// Get the current time
NSCalendarDate *now = [NSCalendarDate calendarDate];
// Update the timeStr
[timeStr release];
timeStr = [[timeFormatter stringFromDate:now] retain];
// Update the shouldDisplaySongInfo variable (if needed)
int elapsedTime = (int)[now timeIntervalSinceDate:startTime];
int statusTime = elapsedTime - statusOffset;
if(statusTime >= 10)
{
statusOffset = elapsedTime;
shouldDisplaySongInfo = !shouldDisplaySongInfo;
}
// Setup the player if needed
if(isDataReady && !isPlayerReady)
{
[self setupPlayer];
if(alarmStatus == STATUS_ACTIVE)
{
[self playerPlay];
}
}
if(alarmStatus == STATUS_ACTIVE)
{
// Set the volume to the proper level
if([lastAlarm usesEasyWake])
{
// typedef double NSTimeInterval: Always in seconds; yields submillisecond precision...
NSTimeInterval elapsed = [now timeIntervalSinceDate:startTime];
float scale = (float)elapsed / (float)easyWakeDuration;
if(scale > 1.0)
{
// We have to make sure the scale doesn't get bigger than 100%
// If it does, the volume may end up higher than maxVolume
scale = 1.0;
}
float diff = maxVolume - minVolume;
float percent = minVolume + (diff * scale);
[self setVolume:percent];
}
else
{
[self setVolume:prefVolume];
}
// Check to see if the alarm has expired
if([now timeIntervalSinceDate:startTime] >= killDuration)
{
NSLog(@"Killing alarm due to inactivity");
// Update alarm status
alarmStatus = STATUS_TERMINATED;
// Stop playing the music
[self playerStop];
// Stop the timer
[timer invalidate];
// Set window so it can be put in the background
[[self window] setLevel:NSNormalWindowLevel];
}
}
else
{
// Check to see if the alarm is done sleeping
if([startTime timeIntervalSinceDate:now] <= 0)
{
// Update the alarm status
alarmStatus = STATUS_ACTIVE;
// Reset the start time
[startTime release];
startTime = [now retain];
// Reset status line variables
statusOffset = 0;
shouldDisplaySongInfo = YES;
// Reset the volume
// The setVolume method automatically takes care of unmuting the volume
if([lastAlarm usesEasyWake])
[self setVolume:minVolume];
else
[self setVolume:prefVolume];
// Start the music up again
[self playerPlay];
// Turn off screensaver
[NSThread detachNewThreadSelector:@selector(runAppleScript:) toTarget:self withObject:nil];
// Set window above all other windows
[[self window] setLevel: NSStatusWindowLevel];
// Bring application, and window to the front
[[self window] makeKeyAndOrderFront:self];
[NSApp activateIgnoringOtherApps:YES];
}
}
[roundedView setNeedsDisplay:YES];
}
// KEYBOARD AND REMOTE EVENTS
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
Invoked when a key on the keyboard is pressed.
**/
- (void)keyDown:(NSEvent *)event
{
unsigned short keyCode = [event keyCode];
if(alarmStatus == STATUS_ACTIVE)
{
// Ignore keyboard events for the first 3 seconds
if([[NSDate date] timeIntervalSinceDate:startTime] >= 3.0)
{
// If they hit the Return or Enter keys
if((keyCode == 36) || (keyCode == 76) || (keyCode == 52))
{
if(anyKeyStops)
[self snooze];
else
[self stop];
}
else if(keyCode == 123)
{
if([player isPlaylist])
{
[self minusButtonClicked];
[roundedView setNeedsDisplay:YES];
}
}
else if(keyCode == 124)
{
if([player isPlaylist])
{
[self plusButtonClicked];
[roundedView setNeedsDisplay:YES];
}
}
else
{
if(anyKeyStops)
[self stop];
else
[self snooze];
}
}
}
else if(alarmStatus == STATUS_SNOOZING)
{
if(([event keyCode] == 69) || ([event keyCode] == 24))
{
// The user hit the plus button
[self plusButtonClicked];
[roundedView setNeedsDisplay:YES];
}
else if(([event keyCode] == 78) || ([event keyCode] == 27))
{
// The user hit the minus button
[self minusButtonClicked];
[roundedView setNeedsDisplay:YES];
}
}
}
/**
Invoked when a button on the remote is pressed.
Note: The WindowManager takes care of invoking this method for all active AlarmControllers.
**/
- (void)appleRemoteButton:(AppleRemoteCookieIdentifier)buttonIdentifier pressedDown:(BOOL)pressedDown
{
if(alarmStatus == STATUS_ACTIVE)
{
// Ignore events for the first 3 seconds
if([[NSDate date] timeIntervalSinceDate:startTime] >= 3.0)
{
if(!pressedDown && (buttonIdentifier == kRemoteButtonPlay))
{
[self snooze];
}
if(!pressedDown && (buttonIdentifier == kRemoteButtonRight))
{
// Go to the next song (if using a playlist)
[self playerNextTrack];
}
else if(!pressedDown && (buttonIdentifier == kRemoteButtonLeft))
{
// Go to the previous song (if using a playlist)
[self playerPreviousTrack];
}
}
}
}
// Helper methods
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setVolume:(float)percent
{
float alteredPercent;
// Some users use the application for reminders (like at work and such)
// Therefore, setting the volume to 0% is just fine
if(percent < 0.00)
alteredPercent = 0.00;
else if(percent > 1.00)
alteredPercent = 1.00;
else
alteredPercent = percent;
if(isDigitalAudio)
{
// It's impossible (as far as I know) to systematically control the output volume
// when using digital audio. You can't even do it within system preferences.
// So instead, we'll do the next best thing.
// Control the output of our ITunesPlayer
[player setVolume:percent];
}
else
{