source: trunk/Cocoa/Pester/Source/PSAlarmSetController.m@ 609

Last change on this file since 609 was 608, checked in by Nicholas Riley, 15 years ago

Display "today" or "tomorrow" when setting an alarm.

File size: 26.7 KB
RevLine 
[21]1//
2// PSAlarmSetController.m
3// Pester
4//
5// Created by Nicholas Riley on Tue Oct 08 2002.
6// Copyright (c) 2002 Nicholas Riley. All rights reserved.
7//
8
9#import "PSAlarmSetController.h"
[34]10#import "PSAlarmAlertController.h"
[102]11#import "PSCalendarController.h"
[53]12#import "PSPowerManager.h"
[102]13#import "PSTimeDateEditor.h"
[133]14#import "PSVolumeController.h"
[21]15#import "NJRDateFormatter.h"
[34]16#import "NJRFSObjectSelector.h"
[53]17#import "NJRIntervalField.h"
[39]18#import "NJRQTMediaPopUpButton.h"
[133]19#import "NJRSoundManager.h"
[364]20#import "NJRValidatingField.h"
[34]21#import "NJRVoicePopUpButton.h"
[53]22#import "NSString-NJRExtensions.h"
23#import "NSAttributedString-NJRExtensions.h"
24#import "NSCalendarDate-NJRExtensions.h"
[21]25
[53]26#import "PSAlerts.h"
[34]27#import "PSDockBounceAlert.h"
28#import "PSScriptAlert.h"
29#import "PSNotifierAlert.h"
30#import "PSBeepAlert.h"
31#import "PSMovieAlert.h"
32#import "PSSpeechAlert.h"
[61]33#import "PSWakeAlert.h"
[34]34
[28]35/* Bugs to file:
[21]36
[28]37¥ any trailing spaces: -> exception for +[NSCalendarDate dateWithNaturalLanguageString]:
38 > NSCalendarDate dateWithNaturalLanguageString: '12 '
39 format error: internal error
[21]40
[28]41¥ NSDate natural language stuff in NSCalendarDate (why?), misspelled category name
42¥ NSCalendarDate natural language stuff behaves differently from NSDateFormatter (AM/PM has no effect, shouldn't they share code?)
[43]43¥ descriptionWithCalendarFormat:, dateWithNaturalLanguageString: does not default to current locale, instead it defaults to US unless you tell it otherwise
[28]44¥ NSDateFormatter doc class description gives two examples for natural language that are incorrect, no link to NSDate doc that describes exactly how natural language dates are parsed
45¥ NSTimeFormatString does not include %p when it should, meaning that AM/PM is stripped yet 12-hour time is still used
46¥ NSNextDayDesignations, NSNextNextDayDesignations are noted as 'a string' in NSUserDefaults docs, but maybe they are actually an array, or either an array or a string, given their names?
47¥ "Setting the Format for Dates" does not document how to get 1:15 AM, the answer is %1I - strftime has no exact equivalent; the closest is %l. strftime does not permit numeric prefixes. It also refers to "NSCalendar" when no such class exists.
[43]48¥ none of many mentions of NSAMPMDesignation indicates that they include the leading spaces (" AM", " PM"). In "Setting the Format for Dates", needs to mention that the leading spaces are not included in %p with strftime. But if you use the NSCalendarDate stuff, it appears %p doesn't include the space (because it doesn't use the locale dictionary).
49¥ If you feed NSCalendarDate dateWithNaturalLanguageString: an " AM"/" PM" locale, it doesn't accept that date format.
[28]50¥ descriptions for %X and %x are reversed (time zone is in %X, not %x)
[53]51¥ NSComboBox data source issues, canÕt have it appear as ÒtodayÓ because the formatter doesnÕt like that. Should be able to enter text into the data source and have the formatter process it without altering it.
[28]52¥ too hard to implement date-only or time-only formatters
53¥ should be able to specify that natural language favors date or time (10 = 10th of month, not 10am)
54¥ please expose the iCal controls!
55
56*/
57
[53]58static NSString * const PSAlertsSelected = @"Pester alerts selected"; // NSUserDefaults key
59static NSString * const PSAlertsEditing = @"Pester alerts editing"; // NSUserDefaults key
60
[26]61@interface PSAlarmSetController (Private)
[21]62
[53]63- (void)_readAlerts:(PSAlerts *)alerts;
64- (BOOL)_setAlerts;
[133]65- (void)_setVolume:(float)volume withPreview:(BOOL)preview;
[26]66- (void)_stopUpdateTimer;
67
68@end
69
[21]70@implementation PSAlarmSetController
71
72- (void)awakeFromNib;
73{
[53]74 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[60]75 NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[26]76 alarm = [[PSAlarm alloc] init];
[21]77 [[self window] center];
[361]78 if ([[removeMessageButton image] size].width != 0)
79 [removeMessageButton setTitle: @""];
[102]80 [PSTimeDateEditor setUpTimeField: timeOfDay dateField: timeDate completions: timeDateCompletions];
[133]81 { // volume defaults, usually overridden by restored alert info
[598]82 float volume = 0.5f;
[133]83 [NJRSoundManager getDefaultOutputVolume: &volume];
84 [self _setVolume: volume withPreview: NO];
85 }
[599]86 [editAlert setState: [defaults boolForKey: PSAlertsEditing]];
[53]87 {
88 NSDictionary *plAlerts = [defaults dictionaryForKey: PSAlertsSelected];
[364]89 PSAlerts *alerts = nil;
[53]90 if (plAlerts == nil) {
91 alerts = [[PSAlerts alloc] initWithPesterVersion1Alerts];
92 } else {
[364]93 @try {
[53]94 alerts = [[PSAlerts alloc] initWithPropertyList: plAlerts];
[364]95 } @catch (NSException *exception) {
96 NSRunAlertPanel(@"Unable to restore alerts", @"Pester could not restore recent alert information for one or more alerts in the Set Alarm window. The default set of alerts will be used instead.\n\n%@", nil, nil, nil, [exception reason]);
[53]97 alerts = [[PSAlerts alloc] initWithPesterVersion1Alerts];
[364]98 }
[53]99 }
100 [self _readAlerts: alerts];
101 }
102 [self inAtChanged: nil]; // by convention, if sender is nil, we're initializing
[34]103 [self playSoundChanged: nil];
104 [self doScriptChanged: nil];
105 [self doSpeakChanged: nil];
[53]106 [self editAlertChanged: nil];
[34]107 [script setFileTypes: [NSArray arrayWithObjects: @"applescript", @"script", NSFileTypeForHFSTypeCode(kOSAFileType), NSFileTypeForHFSTypeCode('TEXT'), nil]];
[60]108 [notificationCenter addObserver: self selector: @selector(silence:) name: PSAlarmAlertStopNotification object: nil];
109 [notificationCenter addObserver: self selector: @selector(playSoundChanged:) name: NJRQTMediaPopUpButtonMovieChangedNotification object: sound];
110 [notificationCenter addObserver: self selector: @selector(applicationWillHide:) name: NSApplicationWillHideNotification object: NSApp];
111 [notificationCenter addObserver: self selector: @selector(applicationDidUnhide:) name: NSApplicationDidUnhideNotification object: NSApp];
[61]112 [notificationCenter addObserver: self selector: @selector(applicationWillTerminate:) name: NSApplicationWillTerminateNotification object: NSApp];
[53]113 [voice setDelegate: self]; // XXX why don't we do this in IB? It should use the accessor...
114 [wakeUp setEnabled: [PSPowerManager autoWakeSupported]];
[522]115
[53]116 // XXX workaround for 10.1.x and 10.2.x bug which sets the first responder to the wrong field alternately, but it works if I set the initial first responder to nil... go figure.
[522]117 NSWindow *window = [self window];
118 [window setInitialFirstResponder: nil];
119 [window makeKeyAndOrderFront: nil];
[21]120}
121
122- (void)setStatus:(NSString *)aString;
123{
[26]124 // NSLog(@"%@", alarm);
[21]125 if (aString != status) {
126 [status release]; status = nil;
127 status = [aString retain];
128 [timeSummary setStringValue: status];
129 }
130}
131
[53]132// XXX with -[NSControl currentEditor] don't need to compare? Also check -[NSControl validateEditing]
[21]133- (id)objectValueForTextField:(NSTextField *)field whileEditing:(id)sender;
134{
135 if (sender == field) {
136 NSString *stringValue = [[[self window] fieldEditor: NO forObject: field] string];
137 id obj = nil;
138 [[field formatter] getObjectValue: &obj forString: stringValue errorDescription: NULL];
139 // NSLog(@"from field editor: %@", obj);
140 return obj;
141 } else {
142 // NSLog(@"from field: %@", [field objectValue]);
143 return [field objectValue];
144 }
145}
146
[53]147#pragma mark date/interval setting
148
[21]149- (void)setAlarmDateAndInterval:(id)sender;
150{
[26]151 if (isInterval) {
[53]152 [alarm setInterval: [timeInterval interval]];
[21]153 } else {
[24]154 [alarm setForDate: [self objectValueForTextField: timeDate whileEditing: sender]
155 atTime: [self objectValueForTextField: timeOfDay whileEditing: sender]];
[21]156 }
157}
158
[26]159- (void)_stopUpdateTimer;
160{
[28]161 [updateTimer invalidate]; [updateTimer release]; updateTimer = nil;
[26]162}
[21]163
[24]164- (IBAction)updateDateDisplay:(id)sender;
[21]165{
[26]166 // NSLog(@"updateDateDisplay: %@", sender);
[608]167 if (![alarm isValid]) {
168 [setButton setEnabled: NO];
169 [self setStatus: [alarm invalidMessage]];
170 [self _stopUpdateTimer];
171 return;
[21]172 }
[608]173
174 const int day = 60 * 60 * 24;
175 int daysUntilAlarm = [alarm daysFromToday];
176 NSString *onString;
177 switch (daysUntilAlarm) {
178 case 0: onString = @"today,"; break;
179 case 1: onString = @"tomorrow,"; break;
180 default: onString = @"on";
181 }
182
183 [self setStatus: [NSString stringWithFormat: @"Alarm will be set for %@\n%@ %@.", [alarm timeString], onString, [alarm dateString]]];
184 [setButton setEnabled: YES];
185 if (updateTimer == nil || ![updateTimer isValid]) {
186 // XXX this logic (and the timer) should really go into PSAlarm, to send notifications for status updates instead. Timer starts when people are watching, stops when people aren't.
187 // NSLog(@"setting timer");
188 if (isInterval) {
189 updateTimer = [NSTimer scheduledTimerWithTimeInterval: 1 target: self selector: @selector(updateDateDisplay:) userInfo: nil repeats: YES];
190 } else {
191 // XXX time/time zone change
192 NSTimeInterval interval = [alarm interval];
193 if (daysUntilAlarm < 2 && interval > day)
194 interval = [[alarm midnightOnDate] timeIntervalSinceNow];
195 updateTimer = [NSTimer scheduledTimerWithTimeInterval: interval target: self selector: @selector(updateDateDisplay:) userInfo: nil repeats: NO];
196 }
197 [updateTimer retain];
198 }
[21]199}
200
[26]201// Be careful not to hook up any of the text fields' actions to update: because we handle them in controlTextDidChange: instead. If we could get the active text field somehow via public API (guess we could use controlTextDidBegin/controlTextDidEndEditing) then we'd not need to overload the update sender for this purpose. Or, I guess, we could use another method other than update. It should not be this hard to implement what is essentially standard behavior. Sigh.
[43]202// Note: finding out whether a given control is editing is easier. See: <http://cocoa.mamasam.com/COCOADEV/2002/03/2/28501.php>.
[26]203
[24]204- (IBAction)update:(id)sender;
205{
206 // NSLog(@"update: %@", sender);
207 [self setAlarmDateAndInterval: sender];
208 [self updateDateDisplay: sender];
209}
210
[21]211- (IBAction)inAtChanged:(id)sender;
212{
[43]213 NSButtonCell *new = [inAtMatrix selectedCell], *old;
[26]214 isInterval = ([inAtMatrix selectedTag] == 0);
[43]215 old = [inAtMatrix cellWithTag: isInterval];
216 NSAssert(new != old, @"in and at buttons should be distinct!");
[364]217
218 if (sender != nil) {
219 // XXX validation doesn't work properly for date/time, so we just universally cancel editing now
220 if (![[self window] makeFirstResponder: nil] && !isInterval) {
221 // This works fine synchronously only if you're using the keyboard shortcut to switch in/at. Directly activating the button, a delayed invocation is necessary.
222 NSInvocation *i = [NSInvocation invocationWithMethodSignature:
223 [inAtMatrix methodSignatureForSelector: @selector(selectCellWithTag:)]];
224 int tag = [old tag];
225 [i setSelector: @selector(selectCellWithTag:)];
226 [i setTarget: inAtMatrix];
227 [i setArgument: &tag atIndex: 2];
228 [NSTimer scheduledTimerWithTimeInterval: 0 invocation: i repeats: NO];
229 return;
230 }
231 }
232
[43]233 [old setKeyEquivalent: [new keyEquivalent]];
234 [old setKeyEquivalentModifierMask: [new keyEquivalentModifierMask]];
235 [new setKeyEquivalent: @""];
236 [new setKeyEquivalentModifierMask: 0];
[26]237 [timeInterval setEnabled: isInterval];
238 [timeIntervalUnits setEnabled: isInterval];
[34]239 [timeIntervalRepeats setEnabled: isInterval];
[26]240 [timeOfDay setEnabled: !isInterval];
241 [timeDate setEnabled: !isInterval];
[361]242 [timeDateCompletions setEnabled: !isInterval && [NJRDateFormatter naturalLanguageParsingAvailable]];
[102]243 [timeCalendarButton setEnabled: !isInterval];
[21]244 if (sender != nil)
[364]245 [[self window] makeFirstResponder: isInterval ? (NSTextField *)timeInterval : timeOfDay];
246 if (!isInterval) // need to do this every time the controls are enabled
[102]247 [timeOfDay setNextKeyView: timeDate];
[21]248 // NSLog(@"UPDATING FROM inAtChanged");
249 [self update: nil];
250}
251
[53]252- (IBAction)dateCompleted:(NSPopUpButton *)sender;
253{
254 [timeDate setStringValue: [sender titleOfSelectedItem]];
255 [self update: sender];
256}
257
[102]258#pragma mark calendar
259
260- (IBAction)showCalendar:(NSButton *)sender;
261{
262 [PSCalendarController controllerWithDate: [NSCalendarDate dateForDay: [timeDate objectValue]] delegate: self];
263}
264
265- (void)calendarController:(PSCalendarController *)calendar didSetDate:(NSCalendarDate *)date;
266{
267 [timeDate setObjectValue: date];
268 [self update: self];
269}
270
271- (NSView *)calendarControllerLaunchingView:(PSCalendarController *)controller;
272{
273 return timeCalendarButton;
274}
275
[133]276#pragma mark volume
277
278- (IBAction)showVolume:(NSButton *)sender;
279{
280 [PSVolumeController controllerWithVolume: [sound outputVolume] delegate: self];
281}
282
283#define VOLUME_IMAGE_INDEX(vol) (vol * 4) - 0.01
284
285- (void)_setVolume:(float)volume withPreview:(BOOL)preview;
286{
287 float outputVolume = [sound outputVolume];
288 short volumeImageIndex = VOLUME_IMAGE_INDEX(volume);
289
290 if (outputVolume > 0 && volumeImageIndex == VOLUME_IMAGE_INDEX(outputVolume)) return;
291 NSString *volumeImageName = [NSString stringWithFormat: @"Volume %ld", volumeImageIndex];
292 [soundVolumeButton setImage: [NSImage imageNamed: volumeImageName]];
293
294 [sound setOutputVolume: volume withPreview: preview];
295}
296
297- (void)volumeController:(PSVolumeController *)controller didSetVolume:(float)volume;
298{
299 [self _setVolume: volume withPreview: YES];
300}
301
302- (NSView *)volumeControllerLaunchingView:(PSVolumeController *)controller;
303{
304 return soundVolumeButton;
305}
306
[53]307#pragma mark alert editing
308
[102]309- (IBAction)toggleAlertEditor:(id)sender;
310{
311 [editAlert performClick: self];
312}
313
[53]314- (IBAction)editAlertChanged:(id)sender;
315{
[579]316 BOOL editAlertSelected = [editAlert state] == NSOnState;
[53]317 NSWindow *window = [self window];
318 NSRect frame = [window frame];
319 if (editAlertSelected) {
320 NSSize editWinSize = [window maxSize];
[579]321 [editAlert setNextKeyView: [displayMessage controlView]];
[53]322 frame.origin.y += frame.size.height - editWinSize.height;
323 frame.size = editWinSize;
324 [window setFrame: frame display: (sender != nil) animate: (sender != nil)];
325 [self updateDateDisplay: sender];
326 [alertTabs selectTabViewItemWithIdentifier: @"edit"];
327 } else {
328 NSSize viewWinSize = [window minSize];
329 NSRect textFrame = [alertView frame];
330 float textHeight;
331 if (![self _setAlerts]) {
[103]332 [alertView setStringValue: [NSString stringWithFormat: @"%@\n%@", NSLocalizedString(@"Couldn't process alert information.", "Message shown in collapsed alert area when alert information is invalid or inconsistent (prevents setting alarm)"), status]];
[53]333 } else {
334 NSAttributedString *string = [[alarm alerts] prettyList];
335 if (string == nil) {
[103]336 [alertView setStringValue: NSLocalizedString(@"Do nothing. Click the button labeled 'Edit' to add an alert.", "Message shown in collapsed alert edit area when no alerts have been specified")];
[53]337 } else {
338 [alertView setAttributedStringValue: string];
339 [self updateDateDisplay: sender];
340 }
341 }
342 if (sender != nil) { // nil == we're initializing, don't mess with focus
343 NSResponder *oldResponder = [window firstResponder];
344 // make sure focus doesn't get stuck in the edit tab: it is confusing and leaves behind artifacts
[606]345 if (oldResponder == editAlert ||
346 ([oldResponder isKindOfClass: [NSView class]] && [(NSView *)oldResponder isDescendantOf: alertTabs]))
[579]347 [window makeFirstResponder: messageField]; // would use editAlert, but can't get it to display anomaly-free.
[53]348 [self silence: sender];
349 }
350 // allow height to expand, though not arbitrarily (should still fit on an 800x600 screen)
351 textHeight = [[alertView cell] cellSizeForBounds: NSMakeRect(0, 0, textFrame.size.width, 400)].height;
352 textFrame.origin.y += textFrame.size.height - textHeight;
353 textFrame.size.height = textHeight;
354 [alertView setFrame: textFrame];
355 viewWinSize.height += textHeight;
356 [alertTabs selectTabViewItemWithIdentifier: @"view"];
357 frame.origin.y += frame.size.height - viewWinSize.height;
358 frame.size = viewWinSize;
359 [window setFrame: frame display: (sender != nil) animate: (sender != nil)];
[579]360 [editAlert setNextKeyView: cancelButton];
[53]361 }
362 if (sender != nil) {
363 [[NSUserDefaults standardUserDefaults] setBool: editAlertSelected forKey: PSAlertsEditing];
364 }
365}
366
[34]367- (IBAction)playSoundChanged:(id)sender;
368{
369 BOOL playSoundSelected = [playSound intValue];
[542]370 BOOL canRepeat = playSoundSelected ? [sound canRepeat] : NO;
[364]371 [sound setEnabled: playSoundSelected];
[41]372 [soundRepetitions setEnabled: canRepeat];
[133]373 [soundVolumeButton setEnabled: canRepeat && [sound hasAudio]];
[41]374 [soundRepetitionStepper setEnabled: canRepeat];
375 [soundRepetitionsLabel setTextColor: canRepeat ? [NSColor controlTextColor] : [NSColor disabledControlTextColor]];
[53]376 if (playSoundSelected && sender == playSound) {
[542]377 [[self window] makeFirstResponder: sound];
[53]378 }
[34]379}
380
[41]381- (IBAction)setSoundRepetitionCount:(id)sender;
382{
[43]383 NSTextView *fieldEditor = (NSTextView *)[soundRepetitions currentEditor];
384 BOOL isEditing = (fieldEditor != nil);
385 int newReps = [sender intValue], oldReps;
386 if (isEditing) {
387 // XXX work around bug where if you ask soundRepetitions for its intValue too often while it's editing, the field begins to flash
388 oldReps = [[[fieldEditor textStorage] string] intValue];
389 } else oldReps = [soundRepetitions intValue];
390 if (newReps != oldReps) {
[41]391 [soundRepetitions setIntValue: newReps];
[43]392 // NSLog(@"updating: new value %d, old value %d%@", newReps, oldReps, isEditing ? @", is editing" : @"");
393 // XXX work around 10.1 bug, otherwise field only displays every second value
394 if (isEditing) [soundRepetitions selectText: self];
395 }
[41]396}
397
[34]398// XXX should check the 'Do script:' button when someone drops a script on the button
399
400- (IBAction)doScriptChanged:(id)sender;
401{
402 BOOL doScriptSelected = [doScript intValue];
403 [script setEnabled: doScriptSelected];
404 [scriptSelectButton setEnabled: doScriptSelected];
[53]405 if (doScriptSelected && sender != nil) {
[34]406 [[self window] makeFirstResponder: scriptSelectButton];
[53]407 if ([script alias] == nil) [scriptSelectButton performClick: sender];
[355]408 } else {
409 [[self window] makeFirstResponder: sender];
[53]410 }
[34]411}
412
413- (IBAction)doSpeakChanged:(id)sender;
414{
[53]415 BOOL doSpeakSelected = [doSpeak state] == NSOnState;
[34]416 [voice setEnabled: doSpeakSelected];
417 if (doSpeakSelected && sender != nil)
418 [[self window] makeFirstResponder: voice];
[355]419 else
420 [[self window] makeFirstResponder: sender];
[34]421}
422
[53]423- (void)_readAlerts:(PSAlerts *)alerts;
[21]424{
[53]425 NSEnumerator *e = [alerts alertEnumerator];
426 PSAlert *alert;
427
428 [alarm setAlerts: alerts];
429
430 // turn off all alerts
431 [bounceDockIcon setState: NSOffState];
432 [doScript setIntValue: NO];
433 [displayMessage setIntValue: NO];
434 [playSound setIntValue: NO];
435 [doSpeak setIntValue: NO];
436
437 while ( (alert = [e nextObject]) != nil) {
438 if ([alert isKindOfClass: [PSDockBounceAlert class]]) {
[522]439 [bounceDockIcon setIntValue: YES]; // temporary for 1.1b8
[53]440 } else if ([alert isKindOfClass: [PSScriptAlert class]]) {
441 [doScript setIntValue: YES];
442 [script setAlias: [(PSScriptAlert *)alert scriptFileAlias]];
443 } else if ([alert isKindOfClass: [PSNotifierAlert class]]) {
444 [displayMessage setIntValue: YES];
[133]445 } else if ([alert isKindOfClass: [PSMediaAlert class]]) {
446 unsigned int repetitions = [(PSMediaAlert *)alert repetitions];
[53]447 [playSound setIntValue: YES];
448 [soundRepetitions setIntValue: repetitions];
449 [soundRepetitionStepper setIntValue: repetitions];
[133]450 [self _setVolume: [(PSMediaAlert *)alert outputVolume] withPreview: NO];
451 if ([alert isKindOfClass: [PSBeepAlert class]]) {
452 [sound setAlias: nil];
453 } else if ([alert isKindOfClass: [PSMovieAlert class]]) {
454 [sound setAlias: [(PSMovieAlert *)alert movieFileAlias]];
455 }
[53]456 } else if ([alert isKindOfClass: [PSSpeechAlert class]]) {
457 [doSpeak setIntValue: YES];
458 [voice setVoice: [(PSSpeechAlert *)alert voice]];
[61]459 } else if ([alert isKindOfClass: [PSWakeAlert class]]) {
460 [wakeUp setIntValue: YES];
[53]461 }
[21]462}
[61]463}
[21]464
[53]465- (BOOL)_setAlerts;
466{
467 PSAlerts *alerts = [alarm alerts];
468
469 [alerts removeAlerts];
[364]470 @try {
[53]471 // dock bounce alert
[522]472 if ([bounceDockIcon intValue]) // temporary for 1.1b8
[53]473 [alerts addAlert: [PSDockBounceAlert alert]];
474 // script alert
475 if ([doScript intValue]) {
476 BDAlias *scriptFileAlias = [script alias];
477 if (scriptFileAlias == nil) {
478 [self setStatus: @"Unable to set script alert (no script specified?)"];
479 return NO;
480 }
481 [alerts addAlert: [PSScriptAlert alertWithScriptFileAlias: scriptFileAlias]];
482 }
483 // notifier alert
484 if ([displayMessage intValue])
485 [alerts addAlert: [PSNotifierAlert alert]];
486 // sound alerts
487 if ([playSound intValue]) {
488 BDAlias *soundAlias = [sound selectedAlias];
489 unsigned short numReps = [soundRepetitions intValue];
[133]490 PSMediaAlert *alert;
[53]491 if (soundAlias == nil) // beep alert
[133]492 alert = [PSBeepAlert alertWithRepetitions: numReps];
[53]493 else // movie alert
[133]494 alert = [PSMovieAlert alertWithMovieFileAlias: soundAlias repetitions: numReps];
495 [alerts addAlert: alert];
496 [alert setOutputVolume: [sound outputVolume]];
[53]497 }
498 // speech alert
499 if ([doSpeak intValue])
[364]500 [alerts addAlert: [PSSpeechAlert alertWithVoice: [[voice selectedItem] representedObject]]];
[61]501 // wake alert
502 if ([wakeUp intValue])
503 [alerts addAlert: [PSWakeAlert alert]];
[53]504 [[NSUserDefaults standardUserDefaults] setObject: [alerts propertyListRepresentation] forKey: PSAlertsSelected];
[364]505 } @catch (NSException *exception) {
506 [self setStatus: [exception reason]];
507 return NO;
508 }
[53]509 return YES;
510}
511
512#pragma mark actions
513
[21]514// to ensure proper updating of interval, this should be the only method by which the window is shown (e.g. from the Alarm menu)
515- (IBAction)showWindow:(id)sender;
516{
[522]517 NSWindow *window = [self window];
518
519 if (![window isVisible]) {
[53]520 NSDate *today = [NSCalendarDate dateForDay: [NSDate date]];
521 if ([(NSDate *)[timeDate objectValue] compare: today] == NSOrderedAscending) {
522 [timeDate setObjectValue: today];
523 }
[21]524 [self update: self];
[53]525 // XXX bug workaround - otherwise, first responder appears to alternate every time the window is shown. And if you set the initial first responder, you can't tab in the window. :(
[522]526 [window makeFirstResponder: [window initialFirstResponder]];
[21]527 }
[522]528
[21]529 [super showWindow: sender];
530}
531
532- (IBAction)setAlarm:(NSButton *)sender;
533{
[45]534 // set alerts before setting alarm...
[53]535 if (![self _setAlerts]) return;
[45]536
537 // set alarm
538 [self setAlarmDateAndInterval: sender];
[53]539 [alarm setRepeating: [timeIntervalRepeats state] == NSOnState];
[45]540 [alarm setMessage: [messageField stringValue]];
541 if (![alarm setTimer]) {
[102]542 [self setStatus: [@"Unable to set alarm. " stringByAppendingString: [alarm invalidMessage]]];
[45]543 return;
544 }
[34]545
[24]546 [self setStatus: [[alarm date] descriptionWithCalendarFormat: @"Alarm set for %x at %X" timeZone: nil locale: nil]];
[21]547 [[self window] close];
[26]548 [alarm release];
549 alarm = [[PSAlarm alloc] init];
[21]550}
551
[34]552- (IBAction)silence:(id)sender;
553{
554 [sound stopSoundPreview: self];
555 [voice stopVoicePreview: self];
556}
557
[102]558- (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)anItem;
559{
560 if ([anItem action] == @selector(toggleAlertEditor:)) {
561 if ([NSApp keyWindow] != [self window])
562 return NO;
563 [(NSMenuItem *)anItem setState: [editAlert intValue] ? NSOnState : NSOffState];
564 }
565 return YES;
566}
567
[26]568@end
569
570@implementation PSAlarmSetController (NSControlSubclassDelegate)
571
[53]572- (BOOL)control:(NSControl *)control didFailToFormatString:(NSString *)string errorDescription:(NSString *)error;
573{
574 if (control == timeInterval)
575 [timeInterval handleDidFailToFormatString: string errorDescription: error label: @"alarm interval"];
[364]576 else if (control == soundRepetitions)
577 [soundRepetitions handleDidFailToFormatString: string errorDescription: error label: @"alert repetitions"];
[53]578 return NO;
579}
580
[26]581- (void)control:(NSControl *)control didFailToValidatePartialString:(NSString *)string errorDescription:(NSString *)error;
582{
583 // NSLog(@"UPDATING FROM validation");
[53]584 if (control == timeInterval) [self update: timeInterval]; // make sure we still examine the field editor, otherwise if the existing numeric string is invalid, it'll be cleared
[26]585}
586
587@end
588
589@implementation PSAlarmSetController (NSWindowNotifications)
590
591- (void)windowWillClose:(NSNotification *)notification;
592{
593 // NSLog(@"stopping update timer");
[34]594 [self silence: nil];
[26]595 [self _stopUpdateTimer];
[53]596 [self _setAlerts];
[26]597}
598
599@end
600
601@implementation PSAlarmSetController (NSControlSubclassNotifications)
602
[21]603// called because we're the delegate
604
[588]605- (void)controlTextDidEndEditing:(NSNotification *)notification;
606{
607 if ([notification object] != timeOfDay)
608 return;
609
610 // if date is today and we've picked a time before now, set the date for tomorrow
611 NSDate *dateTime = [NSCalendarDate dateWithDate: [timeDate objectValue] atTime: [timeOfDay objectValue]];
612 if (dateTime == nil)
613 return;
614
615 NSDate *now = [NSDate date];
616 NSCalendarDate *today = [NSCalendarDate dateForDay: now];
617 NSCalendarDate *date = [NSCalendarDate dateForDay: [timeDate objectValue]];
618 if (![date isEqualToDate: today] || [dateTime compare: now] != NSOrderedAscending)
619 return;
620
621 [timeDate setObjectValue: [today dateByAddingYears: 0 months: 0 days: 1 hours: 0 minutes: 0 seconds: 0]];
622 [self update: timeOfDay];
623}
624
[21]625- (void)controlTextDidChange:(NSNotification *)notification;
626{
[43]627 // NSLog(@"UPDATING FROM controlTextDidChange: %@", [notification object]);
[21]628 [self update: [notification object]];
629}
630
[34]631@end
632
633@implementation PSAlarmSetController (NJRVoicePopUpButtonDelegate)
634
635- (NSString *)voicePopUpButton:(NJRVoicePopUpButton *)sender previewStringForVoice:(NSString *)voice;
636{
[53]637 NSString *message = [messageField stringValue];
638 if (message == nil || [message length] == 0)
639 message = [alarm message];
640 return message;
[34]641}
642
[60]643@end
644
645@implementation PSAlarmSetController (NSApplicationNotifications)
646
[61]647- (void)applicationWillTerminate:(NSNotification *)notification;
648{
649 [self _setAlerts];
650}
651
[60]652- (void)applicationWillHide:(NSNotification *)notification;
653{
654 if ([[self window] isVisible]) {
655 [self silence: nil];
656 [self _stopUpdateTimer];
657 }
658}
659
660- (void)applicationDidUnhide:(NSNotification *)notification;
661{
662 if ([[self window] isVisible]) {
663 [self update: self];
664 }
665}
666
[522]667@end
Note: See TracBrowser for help on using the repository browser.