-
Notifications
You must be signed in to change notification settings - Fork 84
/
ThymeAppDelegate.m
796 lines (626 loc) · 24.3 KB
/
ThymeAppDelegate.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
//
// ThymeAppDelegate.m
// Thyme
//
// Created by João Moreno on 2/8/10.
//
#import "ThymeAppDelegate.h"
#import "Session.h"
#import "ShortcutRecorder/PTHotKey/PTKeyCodeTranslator.h"
#define KEYCODE_T 17
#define KEYCODE_R 15
#define ZERO_TIME (hours == 0 && minutes == 0 && seconds == 0)
@interface ThymeAppDelegate(hidden)
- (void)startTimer;
- (void)resetTimer;
- (void)notifyStart;
- (void)notifyPauseWithDescription:(NSString*)description;
- (void)notifyStopWithDescription:(NSString*)description;
- (void)save:(NSTimeInterval)value : (NSString*)tag;
- (void)updateStatusBar;
- (void)clearSessionsFromMenu;
- (void)addSessionToMenu:(Session*)session;
- (IBAction)clear:(id)sender;
- (IBAction)saveAction:(id)sender;
- (IBAction)okButtonAction:(id)sender;
@end
@implementation ThymeAppDelegate
@synthesize stopwatch;
@synthesize hotKeyCenter;
@synthesize statusItem;
@synthesize window;
@synthesize menu;
@synthesize startPauseItem;
@synthesize restartItem;
@synthesize finishItem;
@synthesize preferencesWindowController;
@synthesize tagWindowController;
@synthesize sessionsMenuSeparator;
@synthesize sessionsMenuExportItem;
@synthesize sessionsMenuClearItem;
@synthesize sessionsMenuItems;
@synthesize lastStopWatchValue;
#pragma mark Controller
- (void)startWithNotification:(Boolean)notification
{
if (![self.stopwatch isActive]) {
[self.stopwatch start];
[startPauseItem setTitle:@"Pause"];
[restartItem setEnabled:YES];
[finishItem setEnabled:YES];
if (notification) {
[self notifyStart];
}
}
}
- (void)pauseWithNotification:(Boolean)notification
{
if ([self.stopwatch isActive]) {
[self.stopwatch pause];
[startPauseItem setTitle:@"Continue"];
if (notification) {
[self notifyPauseWithDescription:[self.stopwatch description]];
}
}
}
- (void)toggleWithNotification:(Boolean)notification
{
if ([self.stopwatch isActive]) {
[self pauseWithNotification:notification];
} else {
[self startWithNotification:notification];
}
}
- (void)stopWithNotification:(Boolean)notification
{
if (![self.stopwatch isStopped]) {
NSString* description = [self.stopwatch description];
[self resetWithNotification:NO];
if (notification) {
[self notifyStopWithDescription:description];
}
}
}
- (void)resetWithNotification:(Boolean)notification
{
if (![self.stopwatch isStopped]) {
NSString* description = [self.stopwatch description];
[self.stopwatch stop];
[startPauseItem setTitle:@"Start"];
[restartItem setEnabled:NO];
[finishItem setEnabled:NO];
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"askForTagOnFinishButton"]) {
//Show tag window
if (self.tagWindowController == nil) {
TagWindowController* pwc = [[TagWindowController alloc] initWithWindowNibName:@"TagWindowController"];
self.tagWindowController = pwc;
[pwc release];
}
[self.tagWindowController showWindow:nil];
}
else{
[self save: lastStopWatchValue : @""];
}
[NSApp activateIgnoringOtherApps:YES];
if (notification) {
[self notifyPauseWithDescription:description];
}
}
}
- (void)restartWithNotification:(Boolean)notification
{
if (![self.stopwatch isStopped]) {
[self resetWithNotification:notification];
[self startWithNotification:notification];
}
}
- (void)clearSessionsFromMenu
{
[menu removeItem:self.sessionsMenuSeparator];
[menu removeItem:self.sessionsMenuExportItem];
[menu removeItem:self.sessionsMenuClearItem];
for (NSMenuItem *item in self.sessionsMenuItems) {
[menu removeItem:item];
}
[self.sessionsMenuItems removeAllObjects];
}
- (void)addSessionToMenu:(Session*)session
{
if ([self.sessionsMenuItems count] == 0)
{
[menu insertItem:self.sessionsMenuSeparator atIndex:3];
[menu insertItem:self.sessionsMenuExportItem atIndex:4];
[menu insertItem:self.sessionsMenuClearItem atIndex:5];
}
NSInteger index = 4 + [self.sessionsMenuItems count];
NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:[session stringRepresentation] action:@selector(lol) keyEquivalent:@""];
[item setEnabled:NO];
[menu insertItem:item atIndex:index];
[self.sessionsMenuItems addObject:item];
[item release];
}
#pragma mark Model
- (void)save:(NSTimeInterval)value :(NSString*)tag {
long totalSeconds = (long) floor(value);
long hours = totalSeconds / 3600;
long minutes = (totalSeconds / 60) % 60;
long seconds = totalSeconds % 60;
NSString* defaultTag = @"";
if (tag && tag.length > 0)
{
defaultTag = tag;
}
if (totalSeconds > 0) {
Session *session = [Session sessionWithSeconds:seconds minutes:minutes hours:hours tag:defaultTag];
[self saveAction:self];
[self addSessionToMenu:session];
}
}
- (IBAction)okButtonAction:(id)sender
{
if([sender isKindOfClass:[NSButton class]]){
NSButton *button = (NSButton *)sender;
if([button.identifier isEqual: @"tagWindowOkButton"]){
[self save: lastStopWatchValue : self.tagWindowController.tagField.stringValue];
}
if (self.tagWindowController) {
[self.tagWindowController close];
}
}
}
- (IBAction)cancelButtonAction:(id)sender
{
if([sender isKindOfClass:[NSButton class]]){
NSButton *button = (NSButton *)sender;
if([button.identifier isEqual: @"tagWindowCancelButton"]){
[self save: lastStopWatchValue : @""];
if (self.tagWindowController) {
[self.tagWindowController close];
}
}
}
}
#pragma mark Status Bar
- (IBAction)onStartPauseClick:(id)sender
{
[self toggleWithNotification:NO];
}
- (IBAction)onRestartClick:(id)sender
{
[self restartWithNotification:NO];
}
- (IBAction)onFinishClick:(id)sender
{
[self resetWithNotification:NO];
}
- (IBAction)clear:(id)sender
{
for (Session *session in [Session allSessions]) {
[self.managedObjectContext deleteObject:session];
}
[self saveAction:self];
[self clearSessionsFromMenu];
}
- (IBAction)onPreferencesClick:(id)sender {
if (self.preferencesWindowController == nil) {
PreferencesWindowController* pwc = [[PreferencesWindowController alloc] initWithWindowNibName:@"PreferencesWindowController"];
self.preferencesWindowController = pwc;
[pwc release];
}
[self.preferencesWindowController showWindow:nil];
[NSApp activateIgnoringOtherApps:YES];
}
- (IBAction)onAboutClick:(id)sender {
[[NSApplication sharedApplication] orderFrontStandardAboutPanel:nil];
[NSApp activateIgnoringOtherApps:YES];
}
- (void)updateStatusBar {
if ([self.stopwatch isStopped]) {
[statusItem setLength:26.0];
[statusItem setTitle:@""];
NSImage *logo = [NSImage imageNamed:@"logo_small"];
[logo setTemplate:YES];
[statusItem setImage: logo];
} else {
[statusItem setLength:[self.stopwatch value] > 3600 ? 72.0 : 46.0];
[statusItem setTitle:[self.stopwatch description]];
[statusItem setImage:nil];
}
}
#pragma mark Export
- (void)export {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:[Session allSessionsAsDictionaries]
options:0
error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSSavePanel *panel = [NSSavePanel savePanel];
[panel setCanCreateDirectories:NO];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
[dateFormatter setLocale:enUSPOSIXLocale];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
[panel setNameFieldStringValue:[NSString stringWithFormat:@"thyme-%@.json", [dateFormatter stringFromDate:[NSDate date]]]];
[dateFormatter release];
if ([panel runModal] == NSModalResponseOK) {
[jsonData writeToURL:[panel URL] atomically:YES];
}
[jsonString release];
}
#pragma mark Hot Key Handlers
- (void)startTimer
{
if (self.preferencesWindowController != nil && [[self.preferencesWindowController window] isVisible]) {
return;
}
[self toggleWithNotification:YES];
}
- (void)restartTimer
{
if (self.preferencesWindowController != nil && [[self.preferencesWindowController window] isVisible]) {
return;
}
[self restartWithNotification:YES];
}
- (void)resetTimer
{
if (self.preferencesWindowController != nil && [[self.preferencesWindowController window] isVisible]) {
return;
}
[self stopWithNotification:YES];
}
#pragma mark Stopwatch Delegate
- (void) didStart:(id)stopwatch {
[self updateStatusBar];
}
- (void) didPause:(id)_stopwatch {
[self updateStatusBar];
}
- (void) didStop:(id)stopwatch withValue:(NSTimeInterval)value {
self.lastStopWatchValue = value;
[self updateStatusBar];
}
- (void) didChange:(id)stopwatch {
[self updateStatusBar];
}
#pragma mark Notifications
- (void)notifyStart
{
[GrowlApplicationBridge notifyWithTitle:@"Thyme" description:@"Started" notificationName:@"start" iconData:nil priority:0 isSticky:NO clickContext:nil];
}
- (void)notifyPauseWithDescription:(NSString*)description
{
[GrowlApplicationBridge notifyWithTitle:@"Thyme" description:[@"Paused at " stringByAppendingString:description] notificationName:@"pause" iconData:nil priority:0 isSticky:NO clickContext:nil];
}
- (void)notifyStopWithDescription:(NSString*)description
{
[GrowlApplicationBridge notifyWithTitle:@"Thyme" description:[@"Stopped at " stringByAppendingString:description] notificationName:@"stop" iconData:nil priority:0 isSticky:NO clickContext:nil];
}
#pragma mark NSUserDefaultsDidChangeNotification
- (void)onUserDefaultsChange:(NSNotification*)notification {
[self resetHotKeys];
}
#pragma mark Hot Keys
- (void)clearHotKeys {
[self.hotKeyCenter unregisterHotKeysWithTarget:self];
self.startPauseItem.keyEquivalent = @"";
self.startPauseItem.keyEquivalentModifierMask = 0;
self.restartItem.keyEquivalent = @"";
self.restartItem.keyEquivalentModifierMask = 0;
self.finishItem.keyEquivalent = @"";
self.finishItem.keyEquivalentModifierMask = 0;
}
- (void)resetHotKeys {
[self clearHotKeys];
NSDictionary* combo;
NSInteger keyCode;
NSUInteger modifierKeys;
// Start, pause
if ((combo = [[NSUserDefaults standardUserDefaults] valueForKey:@"startPause"]) != nil) {
keyCode = [[combo valueForKey:@"keyCode"] integerValue];
modifierKeys = [[combo valueForKey:@"modifierFlags"] unsignedIntegerValue];
[self.hotKeyCenter registerHotKeyWithKeyCode:keyCode modifierFlags:modifierKeys target:self action:@selector(startTimer) object:nil];
self.startPauseItem.keyEquivalent = [[PTKeyCodeTranslator currentTranslator] translateKeyCode:keyCode];
self.startPauseItem.keyEquivalentModifierMask = modifierKeys;
}
// Restart
if ((combo = [[NSUserDefaults standardUserDefaults] valueForKey:@"restart"]) != nil) {
keyCode = [[combo valueForKey:@"keyCode"] integerValue];
modifierKeys = [[combo valueForKey:@"modifierFlags"] unsignedIntegerValue];
[self.hotKeyCenter registerHotKeyWithKeyCode:keyCode modifierFlags:modifierKeys target:self action:@selector(restartTimer) object:nil];
self.restartItem.keyEquivalent = [[PTKeyCodeTranslator currentTranslator] translateKeyCode:keyCode];
self.restartItem.keyEquivalentModifierMask = modifierKeys;
}
// Finish
if ((combo = [[NSUserDefaults standardUserDefaults] valueForKey:@"finish"]) != nil) {
keyCode = [[combo valueForKey:@"keyCode"] integerValue];
modifierKeys = [[combo valueForKey:@"modifierFlags"] unsignedIntegerValue];
[self.hotKeyCenter registerHotKeyWithKeyCode:keyCode modifierFlags:modifierKeys target:self action:@selector(resetTimer) object:nil];
self.finishItem.keyEquivalent = [[PTKeyCodeTranslator currentTranslator] translateKeyCode:keyCode];
self.finishItem.keyEquivalentModifierMask = modifierKeys;
}
}
#pragma mark Sleep/Wake
- (void) onSleep: (NSNotification*) note
{
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"pauseOnSleep"]) {
startOnWake = [self.stopwatch isActive];
[self pauseWithNotification:NO];
}
}
- (void) onWake: (NSNotification*) note
{
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"pauseOnSleep"] && startOnWake) {
startOnWake = NO;
[self startWithNotification:NO];
}
}
#pragma mark Screensaver
- (void) onScreensaverStart: (NSNotification*) note
{
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"pauseOnScreensaver"]) {
startOnScreensaverEnd = [self.stopwatch isActive];
[self pauseWithNotification:NO];
}
}
- (void) onScreensaverStop: (NSNotification*) note
{
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"pauseOnScreensaver"] && startOnScreensaverEnd) {
startOnScreensaverEnd = NO;
[self startWithNotification:NO];
}
}
#pragma mark NSApplication
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
[window close];
startOnWake = NO;
startOnScreensaverEnd = NO;
// Setup the hotkey center
DDHotKeyCenter *center = [[DDHotKeyCenter alloc] init];
self.hotKeyCenter = center;
[center release];
// Setup Growl
[GrowlApplicationBridge setGrowlDelegate:self];
// Setup user defaults notification
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onUserDefaultsChange:) name:NSUserDefaultsDidChangeNotification object:nil];
// Setup defaults
NSDictionary *defaults = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"defaults" ofType:@"plist"]];
[[NSUserDefaults standardUserDefaults] registerDefaults:defaults];
[[NSUserDefaultsController sharedUserDefaultsController] setInitialValues:defaults];
// Listen to sleep/wake
[[[NSWorkspace sharedWorkspace] notificationCenter]
addObserver:self
selector:@selector(onSleep:)
name:NSWorkspaceWillSleepNotification
object:nil];
[[[NSWorkspace sharedWorkspace] notificationCenter]
addObserver:self
selector:@selector(onWake:)
name:NSWorkspaceDidWakeNotification
object:nil];
// Listen to screensaver
[[NSDistributedNotificationCenter defaultCenter]
addObserver:self
selector:@selector(onScreensaverStart:)
name:@"com.apple.screensaver.didstart"
object:nil];
[[NSDistributedNotificationCenter defaultCenter]
addObserver:self
selector:@selector(onScreensaverStop:)
name:@"com.apple.screensaver.didstop"
object:nil];
[[NSDistributedNotificationCenter defaultCenter]
addObserver:self
selector:@selector(onScreensaverStart:)
name:@"com.apple.screenIsLocked"
object:nil];
[[NSDistributedNotificationCenter defaultCenter]
addObserver:self
selector:@selector(onScreensaverStop:)
name:@"com.apple.screenIsUnlocked"
object:nil];
// Create class attributes
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:20];
self.sessionsMenuItems = array;
[array release];
self.sessionsMenuSeparator = [NSMenuItem separatorItem];
NSMenuItem *clearMenuItem = [[NSMenuItem alloc] initWithTitle:@"Clear" action:@selector(clear:) keyEquivalent:@""];
self.sessionsMenuClearItem = clearMenuItem;
[clearMenuItem release];
NSMenuItem *exportMenuItem = [[NSMenuItem alloc] initWithTitle:@"Export..." action:@selector(export) keyEquivalent:@""];
self.sessionsMenuExportItem = exportMenuItem;
[exportMenuItem release];
self.stopwatch = [[Stopwatch alloc] initWithDelegate:self];
NSStatusBar *statusBar = [NSStatusBar systemStatusBar];
self.statusItem = [statusBar statusItemWithLength:46.0];
[statusItem setHighlightMode:YES];
[statusItem setMenu:menu];
[self updateStatusBar];
// Populate data
for (Session *session in [Session allSessions]) {
[self addSessionToMenu:session];
}
// Start controller
[self resetWithNotification:NO];
}
/**
Returns the support directory for the application, used to store the Core Data
store file. This code uses a directory named "Lol" for
the content, either in the NSApplicationSupportDirectory location or (if the
former cannot be found), the system's temporary directory.
*/
- (NSString *)applicationSupportDirectory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : NSTemporaryDirectory();
return [basePath stringByAppendingPathComponent:@"Thyme"];
}
/**
Creates, retains, and returns the managed object model for the application
by merging all of the models found in the application bundle.
*/
- (NSManagedObjectModel *)managedObjectModel
{
if (managedObjectModel)
return managedObjectModel;
managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];
return managedObjectModel;
}
/**
Returns the persistent store coordinator for the application. This
implementation will create and return a coordinator, having added the
store for the application to it. (The directory for the store is created,
if necessary.)
*/
- (NSPersistentStoreCoordinator *) persistentStoreCoordinator
{
if (persistentStoreCoordinator)
return persistentStoreCoordinator;
NSManagedObjectModel *mom = [self managedObjectModel];
if (!mom)
{
NSAssert(NO, @"Managed object model is nil");
NSLog(@"%@: No model to generate a store from", [self class]);
return nil;
}
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *applicationSupportDirectory = [self applicationSupportDirectory];
NSError *error = nil;
if ( ![fileManager fileExistsAtPath:applicationSupportDirectory isDirectory:NULL] )
{
if (![fileManager createDirectoryAtPath:applicationSupportDirectory withIntermediateDirectories:NO attributes:nil error:&error])
{
NSAssert(NO, ([NSString stringWithFormat:@"Failed to create App Support directory %@ : %@", applicationSupportDirectory,error]));
NSLog(@"Error creating application support directory at %@ : %@",applicationSupportDirectory,error);
return nil;
}
}
NSURL *url = [NSURL fileURLWithPath: [applicationSupportDirectory stringByAppendingPathComponent: @"storedata"]];
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: mom];
if (![persistentStoreCoordinator addPersistentStoreWithType:NSXMLStoreType
configuration:nil
URL:url
options:nil
error:&error])
{
[[NSApplication sharedApplication] presentError:error];
[persistentStoreCoordinator release], persistentStoreCoordinator = nil;
return nil;
}
return persistentStoreCoordinator;
}
/**
Returns the managed object context for the application (which is already
bound to the persistent store coordinator for the application.)
*/
- (NSManagedObjectContext *) managedObjectContext
{
if (managedObjectContext)
return managedObjectContext;
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (!coordinator)
{
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setValue:@"Failed to initialize the store" forKey:NSLocalizedDescriptionKey];
[dict setValue:@"There was an error building up the data file." forKey:NSLocalizedFailureReasonErrorKey];
NSError *error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
[[NSApplication sharedApplication] presentError:error];
return nil;
}
managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator: coordinator];
return managedObjectContext;
}
/**
Returns the NSUndoManager for the application. In this case, the manager
returned is that of the managed object context for the application.
*/
- (NSUndoManager *)windowWillReturnUndoManager:(NSWindow *)window
{
return [[self managedObjectContext] undoManager];
}
/**
Performs the save action for the application, which is to send the save:
message to the application's managed object context. Any encountered errors
are presented to the user.
*/
- (IBAction) saveAction:(id)sender
{
NSError *error = nil;
if (![[self managedObjectContext] commitEditing])
{
NSLog(@"%@: unable to commit editing before saving", [self class]);
}
if (![[self managedObjectContext] save:&error])
{
[[NSApplication sharedApplication] presentError:error];
}
}
/**
Implementation of the applicationShouldTerminate: method, used here to
handle the saving of changes in the application managed object context
before the application terminates.
*/
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
{
if (!managedObjectContext)
return NSTerminateNow;
[self.stopwatch stop];
if (![managedObjectContext commitEditing])
{
NSLog(@"%@: unable to commit editing to terminate", [self class]);
return NSTerminateCancel;
}
if (![managedObjectContext hasChanges])
return NSTerminateNow;
NSError *error = nil;
if (![managedObjectContext save:&error])
{
// This error handling simply presents error information in a panel with an
// "Ok" button, which does not include any attempt at error recovery (meaning,
// attempting to fix the error.) As a result, this implementation will
// present the information to the user and then follow up with a panel asking
// if the user wishes to "Quit Anyway", without saving the changes.
// Typically, this process should be altered to include application-specific
// recovery steps.
BOOL result = [sender presentError:error];
if (result)
return NSTerminateCancel;
NSString *question = NSLocalizedString(@"Could not save changes while quitting. Quit anyway?", @"Quit without saves error question message");
NSString *info = NSLocalizedString(@"Quitting now will lose any changes you have made since the last successful save", @"Quit without saves error question info");
NSString *quitButton = NSLocalizedString(@"Quit anyway", @"Quit anyway button title");
NSString *cancelButton = NSLocalizedString(@"Cancel", @"Cancel button title");
NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:question];
[alert setInformativeText:info];
[alert addButtonWithTitle:quitButton];
[alert addButtonWithTitle:cancelButton];
NSInteger answer = [alert runModal];
[alert release];
alert = nil;
if (answer == NSAlertSecondButtonReturn)
return NSTerminateCancel;
}
return NSTerminateNow;
}
/**
Implementation of dealloc, to release the retained variables.
*/
- (void)dealloc
{
[window release];
[managedObjectContext release];
[persistentStoreCoordinator release];
[managedObjectModel release];
self.stopwatch = nil;
[statusItem release];
[hotKeyCenter release];
[sessionsMenuSeparator release];
[sessionsMenuExportItem release];
[sessionsMenuClearItem release];
[sessionsMenuItems release];
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
@end