-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathMainController.m
1798 lines (1567 loc) · 53.7 KB
/
MainController.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
#include <IOKit/IOKitLib.h>
#import <AppKit/NSTableColumn.h>
#include <assert.h>
#import "MainController.h"
#import "TTask.h"
#import "IProject.h"
#import "TProject.h"
#import "TimeIntervalFormatter.h"
#import "TWorkPeriod.h"
#import "TMetaProject.h"
#import "TDateTransformer.h"
#import "StartTaskMenuDelegate.h"
@implementation MainController
// this flag toggles whether we show tasks in the "All Projects View"
// that have no matching time entries (1 means that these will NOT be shown)
// 0 means that empty tasks will also be shown.
#define ONLY_NON_NULL_TASKS_FOR_OVERVIEW 1
//#define USE_EXTENDED_TOOLBAR
- (id) init
{
if ((self = [super init]) == nil) {
return nil;
}
_maxLruSize = DEFAULT_LRU_SIZE;
_projects = [NSMutableArray new];
_selProject = nil;
_selTask = nil;
_curTask = nil;
_curProject = nil;
_curWorkPeriod = nil;
_idleTimeoutSeconds = 5*60; // DEFAULT 5 minutes
_enableStandbyDetection = YES;
_showTimeInMenuBar = NO;
timer = nil;
timeSinceSave = 0;
_autosaveCsv = YES;
_lruTasks = [[NSMutableArray alloc] initWithCapacity:_maxLruSize+1];
[self setAutosaveCsvFilename:[@"~/times.csv" stringByExpandingTildeInPath]];
_csvSeparatorChar = [@";" retain];
_metaProject = [[TMetaProject alloc] init];
_metaTask = [[TMetaTask alloc] init];
[_metaProject setProjects: _projects];
[_metaTask setTasks: [_metaProject tasks]];
[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehavior10_4];
_dateFormatter = [[NSDateFormatter alloc] init];
[_dateFormatter setDateStyle:NSDateFormatterShortStyle];
[_dateFormatter setTimeStyle:NSDateFormatterNoStyle];
_timeValueFormatter = [[TTimeTransformer alloc] init];
_dateValueFormatter = [[TDateTransformer alloc] init];
_intervalValueFormatter = [[TimeIntervalFormatter alloc] init];
[NSValueTransformer setValueTransformer:_timeValueFormatter forName:@"TimeToStringFormatter"];
[NSValueTransformer setValueTransformer:_dateValueFormatter forName:@"DateToStringFormatter"];
[NSValueTransformer setValueTransformer:_intervalValueFormatter forName:@"TimeIntervalToStringFormatter"];
_selectedfilterDate = nil;
_startMenu = [[NSMenu alloc] initWithTitle:@"TimeTracker"];
StartTaskMenuDelegate *delegate = [[StartTaskMenuDelegate alloc] initWithController:self];
[_startMenu setDelegate:delegate];
[self loadData];
return self;
}
- (NSPredicate*) filterPredicate
{
if (_currentPredicate == nil) {
[self determineFilterStartDate];
[self determineFilterEndDate];
NSString *commentFilter = [_searchBox stringValue];
if ([[_searchBox stringValue] length] > 0) {
if (_filterMode == FILTER_MODE_NONE) {
_currentPredicate = [[NSPredicate predicateWithFormat:
@"comment.string contains[cd] %@",
commentFilter] retain];
// NSLog(@"comment.string contains[cd] %@", commentFilter);
} else {
_currentPredicate = [[NSPredicate predicateWithFormat:
@"startTime >= %@ AND endTime <= %@ AND comment.string contains[cd] %@",
_filterStartDate, _filterEndDate, commentFilter] retain];
// NSLog(@"startTime >= %@ AND endTime <= %@ AND comment.string contains[cd] %@",
// _filterStartDate, _filterEndDate, commentFilter);
}
} else if (_filterMode != FILTER_MODE_NONE) {
_currentPredicate = [[NSPredicate predicateWithFormat: @"startTime >= %@ AND endTime <= %@",
_filterStartDate, _filterEndDate] retain];
//NSLog(@"startTime >= %@ AND endTime <= %@", _filterStartDate, _filterEndDate);
} // otherwise the filterpredicate will stay nil
}
return _currentPredicate;
}
- (void) invalidateFilterPredicate
{
[_currentPredicate release];
_currentPredicate = nil;
}
- (void) applyFilter
{
[workPeriodController setFilterPredicate:[self filterPredicate]];
[self updateTaskFilterCache];
[tvTasks reloadData];
[tvProjects reloadData];
[self validateToolbarFilterItems];
}
- (void) setFilterMode:(int)filterMode
{
_filterMode = filterMode;
[self invalidateFilterPredicate];
}
- (void) validateToolbarFilterItems
{
[_dayToolbarItem setImage: (_filterMode == FILTER_MODE_DAY)? dayToolImageUnsel : dayToolImage];
[_weekToolbarItem setImage: (_filterMode == FILTER_MODE_WEEK)? weekToolImageUnsel : weekToolImage];
[_monthToolbarItem setImage: (_filterMode == FILTER_MODE_MONTH)? monthToolImageUnsel : monthToolImage];
}
- (int) selectedTaskRow
{
return [tvTasks selectedRow] - 1;
}
- (int)selectedProjectRow
{
return [tvProjects selectedRow] - 1;
}
- (int)selectedWorkPeriodRow
{
return [workPeriodController selectionIndex];
}
- (IBAction)clickedStartStopTimer:(id)sender
{
if (timer == nil) {
if (_selTask != nil && [_selTask isKindOfClass:[TTask class]]
&& _selProject != _metaProject) {
[self startTimer];
} else {
NSBeep();
}
} else {
[self stopTimer];
}
}
- (BOOL)validateMenuItem:(NSMenuItem *) anItem {
return YES;
}
- (void)addTaskToLruCache:(TTask*) task
{
[_lruTasks removeObject:task];
[_lruTasks insertObject:task atIndex:0];
while ([_lruTasks count] > _maxLruSize) {
[_lruTasks removeLastObject];
}
}
- (void)selectTask:(TTask*)task project:(TProject*) project
{
_selTask = task;
_selProject = project;
_curProject = project;
_curTask = task;
[self addTaskToLruCache:task];
}
- (void)startTimer
{
assert([_selTask isKindOfClass:[TTask class]]);
// assert timer == nil
if (timer != nil) return;
// if there is no project selected, create a new one
if (_selProject == nil)
[self createProject];
// if there is no task selected, create a new one
if (_selTask == nil)
[self createTask];
timer = [NSTimer scheduledTimerWithTimeInterval: 1 target: self selector: @selector (timerFunc:)
userInfo: nil repeats: YES];
[self updateStartStopState];
_curWorkPeriod = [TWorkPeriod new];
[_curWorkPeriod setStartTime: [NSDate date]];
[_curWorkPeriod setEndTime: [NSDate date]];
[(TTask*)_selTask addWorkPeriod: _curWorkPeriod];
[tvWorkPeriods reloadData];
// make sure the controller knows about the new object
[workPeriodController rearrangeObjects];
[self selectTask:(TTask*)_selTask project:(TProject*)_selProject];
[self updateProminentDisplay];
// assert timer != nil
// assert _curProject != nil
// assert _curTask != nil
}
- (void)stopTimer
{
[self stopTimer:[NSDate date]];
}
- (void)stopTimer:(NSDate*)endTime
{
// assert timer != nil
if (timer == nil) return;
[timer invalidate];
timer = nil;
[_curWorkPeriod setEndTime:endTime];
[_curTask updateTotalTime];
[_curProject updateTotalTime];
_curWorkPeriod = nil;
_curProject = nil;
_curTask = nil;
[self saveData];
[self updateStartStopState];
[tvProjects reloadData];
[tvTasks reloadData];
[tvWorkPeriods reloadData];
[self updateProminentDisplay];
//[defaults setObject: [NSNumber numberWithInt: totalTime] forKey: @"TotalTime"];
// assert timer == nil
// assert _curProject == nil
// assert _curTask == nil
}
- (void)toolbarWillAddItem:(NSNotification *)notification
{
}
- (void)toolbarDidRemoveItem:(NSNotification *)notification
{
}
- (NSToolbarItem *)toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)itemIdentifier willBeInsertedIntoToolbar:(BOOL)flag
{
NSToolbarItem *toolbarItem = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdentifier] autorelease];
if ([itemIdentifier isEqualToString: @"Startstop"]) {
startstopToolbarItem = toolbarItem;
[toolbarItem setTarget:self];
[toolbarItem setAction:@selector(clickedStartStopTimer:)];
[self updateStartStopState];
}
if ([itemIdentifier isEqualToString: @"AddProject"]) {
[toolbarItem setLabel:@"New project"];
[toolbarItem setPaletteLabel:@"New project"];
[toolbarItem setToolTip:@"New project"];
[toolbarItem setImage: addProjectToolImage];
[toolbarItem setTarget:self];
[toolbarItem setAction:@selector(clickedAddProject:)];
}
if ([itemIdentifier isEqualToString: @"AddTask"]) {
[toolbarItem setLabel:@"New task"];
[toolbarItem setPaletteLabel:@"New task"];
[toolbarItem setToolTip:@"New task"];
[toolbarItem setImage: addTaskToolImage];
[toolbarItem setTarget:self];
[toolbarItem setAction:@selector(clickedAddTask:)];
}
if ([itemIdentifier isEqualToString: @"Day"]) {
_dayToolbarItem = [toolbarItem retain];
[toolbarItem setLabel:@"Day"];
[toolbarItem setPaletteLabel:@"Day"];
[toolbarItem setToolTip:@"Filter Day"];
[toolbarItem setImage: dayToolImage];
[toolbarItem setTarget:self];
[toolbarItem setAction:@selector(clickedFilterDay:)];
}
if ([itemIdentifier isEqualToString: @"Week"]) {
_weekToolbarItem = [toolbarItem retain];
[toolbarItem setLabel:@"Week"];
[toolbarItem setPaletteLabel:@"Week"];
[toolbarItem setToolTip:@"Filter Week"];
[toolbarItem setImage: weekToolImage];
[toolbarItem setTarget:self];
[toolbarItem setAction:@selector(clickedFilterWeek:)];
}
if ([itemIdentifier isEqualToString: @"Month"]) {
_monthToolbarItem = [toolbarItem retain];
[toolbarItem setLabel:@"Month"];
[toolbarItem setPaletteLabel:@"Month"];
[toolbarItem setToolTip:@"Filter Month"];
[toolbarItem setImage: monthToolImage];
[toolbarItem setTarget:self];
[toolbarItem setAction:@selector(clickedFilterMonth:)];
}
if ([itemIdentifier isEqualToString: @"PickDate"]) {
[toolbarItem setLabel:@"PickDate"];
[toolbarItem setPaletteLabel:@"PickDate"];
[toolbarItem setToolTip:@"PickDate to filter"];
[toolbarItem setImage: pickDateToolImage];
[toolbarItem setTarget:self];
[toolbarItem setAction:@selector(clickedFilterPickDate:)];
_tbPickDateItem = toolbarItem;
}
#ifdef USE_EXTENDED_TOOLBAR
if ([itemIdentifier isEqualToString: @"FilterDate"]) {
[toolbarItem setLabel:@"Filter Date"];
[toolbarItem setPaletteLabel:@"Filter Date"];
[toolbarItem setToolTip:@"Pick Date to filter"];
// [toolbarItem setImage: pickDateToolImage];
[toolbarItem setTarget:self];
// [toolbarItem setAction:@selector(clickedFilterPickDate:)];
NSDatePicker *picker = [[NSDatePicker alloc] initWithFrame:NSMakeRect(0, 0, 160, 27)];
// 27 is taken from interface builder
// TODO should be more dynamic
[picker setDatePickerStyle:NSTextFieldAndStepperDatePickerStyle];
[toolbarItem setView:picker];
[picker release];
}
#endif // USE_EXTENDED_TOOLBAR
if ([itemIdentifier isEqualToString: @"CommentSearchField"]) {
[toolbarItem setPaletteLabel:@"Filter Comments"];
[toolbarItem setToolTip:@"Enter a text to filter for comments"];
_searchBox = [[NSSearchField alloc] initWithFrame:NSMakeRect(0, 0, 160, 27)];
// 27 is taken from interface builder
// TODO should be more dynamic
[[_searchBox cell] setPlaceholderString:@"Filter Comments"];
[_searchBox setAction:@selector(filterComments:)];
[_searchBox setTarget:self];
[toolbarItem setView:_searchBox];
}
return toolbarItem;
}
- (IBAction)filterComments: (id)sender
{
[self invalidateFilterPredicate];
[self applyFilter];
}
- (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)toolbar
{
return [NSArray arrayWithObjects: @"Startstop", NSToolbarSeparatorItemIdentifier, @"AddProject", @"AddTask",
NSToolbarSeparatorItemIdentifier, @"Day", @"Week", @"Month", @"PickDate", @"FilterDate",
@"CommentSearchField", nil];
}
- (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)toolbar
{
return [NSArray arrayWithObjects: @"Startstop", NSToolbarSeparatorItemIdentifier, @"AddProject", @"AddTask",
NSToolbarSeparatorItemIdentifier, @"Day", @"Week", @"Month", @"PickDate", @"FilterDate",
NSToolbarFlexibleSpaceItemIdentifier, @"CommentSearchField", nil];
}
- (NSArray *)toolbarSelectableItemIdentifiers:(NSToolbar *)toolbar
{
return nil;
}
-(void) loadData
{
NSData *theData = nil;
NSMutableArray *projects = nil;
NSData *indexData = nil;
if ([self dataFileExists]) {
NSString * path = [self pathForDataFile];
NSDictionary * rootObject;
rootObject = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
theData = [rootObject valueForKey:@"ProjectTimes"];
if (theData != nil) {
projects = (NSMutableArray *)[[NSMutableArray arrayWithArray: [NSKeyedUnarchiver unarchiveObjectWithData:theData]] retain];
}
NSString* autosave = [rootObject valueForKey:@"autosave"];
if ([@"NO" isEqualToString:autosave]) {
_autosaveCsv = NO;
} else {
_autosaveCsv = YES;
}
NSString* showTime = [rootObject valueForKey:@"showTimeInMenuBar"];
if ([@"NO" isEqualToString:showTime]) {
_showTimeInMenuBar = NO;
} else {
_showTimeInMenuBar = YES;
}
NSString *autosaveFilename = [rootObject valueForKey:@"autosaveCsvFilename"];
if (autosaveFilename != nil) {
[self setAutosaveCsvFilename:autosaveFilename];
}
NSString *csvSeparator = [rootObject valueForKey:@"separator"];
if (csvSeparator != nil) {
[self setCsvSeparatorChar:csvSeparator];
}
NSString* strLruCount = [rootObject valueForKey:@"lruEntryCount"];
if (strLruCount != nil) {
int value = [strLruCount intValue];
if (value > 2 && value < 99) {
_maxLruSize = value;
}
}
NSString* strIdleTimeout = [rootObject valueForKey:@"idleTimeout"];
if (strIdleTimeout != nil) {
int value = [strIdleTimeout intValue];
[self setIdleTimeoutSeconds:value];
}
NSString* strStandbyDetection = [rootObject valueForKey:@"standbyDetection"];
if ([@"NO" isEqualToString:strStandbyDetection]) {
_enableStandbyDetection = NO;
} else {
_enableStandbyDetection = YES;
}
// restore the lruCache
indexData = [rootObject valueForKey:@"lruIndexes"];
} else {
// use the old unarchiver
defaults = [NSUserDefaults standardUserDefaults];
theData=[[NSUserDefaults standardUserDefaults] dataForKey:@"ProjectTimes"];
if (theData != nil) {
projects = (NSMutableArray *)[[NSMutableArray arrayWithArray: [NSUnarchiver unarchiveObjectWithData:theData]] retain];
}
}
if (projects != nil) {
[_projects release];
// projects is already retained
_projects = projects;
[_metaProject setProjects:_projects];
[_metaTask setTasks:[_metaProject tasks]];
}
// restore lru cache
if (indexData != nil) {
int count = [indexData length] / sizeof(int);
const int *ptrData = (const int*) [indexData bytes];
int i = 0;
for (i = 0; i < count && i < _maxLruSize; i++) {
int taskId = NSSwapBigIntToHost(*ptrData);
ptrData++;
TTask *task = [self findTaskById:taskId];
if (task != nil) {
[_lruTasks addObject:task];
} else {
NSLog(@"task is nil for id: %d",taskId);
}
}
}
_projects_lastTask = [[NSMutableDictionary alloc] initWithCapacity:[_projects count]];
// check projects for duplicate names
NSEnumerator *projectEnum = [_projects objectEnumerator];
int i = 0;
int j = 0;
int uniqueMaker = 1;
TProject *project;
while ((project = [projectEnum nextObject]) != nil) {
for (j = 0; j < i; j++) {
TProject *checkProject = [_projects objectAtIndex:j];
if ([[checkProject name] isEqualToString:[project name]]) {
// duplicate name detected
[checkProject setName:[NSString stringWithFormat:@"%@ %d",[checkProject name], uniqueMaker++]];
}
}
i++;
}
}
- (void)awakeFromNib
{
//NSNumber *numTotalTime = [defaults objectForKey: @"TotalTime"];
/*NSZone *menuZone = [NSMenu menuZone];
NSMenu *m = [[NSMenu allocWithZone:menuZone] init];
startStopMenuItem = (NSMenuItem *)[m addItemWithTitle:@"Start" action:@selector(clickedStartStopTimer:) keyEquivalent:@""];
[startStopMenuItem setTarget:self];
[startStopMenuItem setTag:1];*/
/*if ([preferences isGrowlRunning]) {
[tempMenuItem setTitle:kRestartGrowl];
[tempMenuItem setToolTip:kRestartGrowlTooltip];
} else {
[tempMenuItem setToolTip:kStartGrowlTooltip];
}
tempMenuItem = (NSMenuItem *)[m addItemWithTitle:kStopGrowl action:@selector(stopGrowl:) keyEquivalent:@""];
[tempMenuItem setTag:2];
[tempMenuItem setTarget:self];
[tempMenuItem setToolTip:kStopGrowlTooltip];
tempMenuItem = (NSMenuItem *)[m addItemWithTitle:kStopGrowlMenu action:@selector(terminate:) keyEquivalent:@""];
[tempMenuItem setTag:5];
[tempMenuItem setTarget:NSApp];
[tempMenuItem setToolTip:kStopGrowlMenuTooltip];
[m addItem:[NSMenuItem separatorItem]];
tempMenuItem = (NSMenuItem *)[m addItemWithTitle:kSquelchMode action:@selector(squelchMode:) keyEquivalent:@""];
[tempMenuItem setTarget:self];
[tempMenuItem setTag:4];
[tempMenuItem setToolTip:kSquelchModeTooltip];
NSMenu *displays = [[NSMenu allocWithZone:menuZone] init];
NSString *name;
NSEnumerator *displayEnumerator = [[[GrowlPluginController controller] allDisplayPlugins] objectEnumerator];
while ((name = [displayEnumerator nextObject])) {
tempMenuItem = (NSMenuItem *)[displays addItemWithTitle:name action:@selector(defaultDisplay:) keyEquivalent:@""];
[tempMenuItem setTarget:self];
[tempMenuItem setTag:3];
}
tempMenuItem = (NSMenuItem *)[m addItemWithTitle:kDefaultDisplay action:NULL keyEquivalent:@""];
[tempMenuItem setTarget:self];
[tempMenuItem setSubmenu:displays];
[displays release];
[m addItem:[NSMenuItem separatorItem]];
tempMenuItem = (NSMenuItem *)[m addItemWithTitle:kOpenGrowlPreferences action:@selector(openGrowlPreferences:) keyEquivalent:@""];
[tempMenuItem setTarget:self];
[tempMenuItem setToolTip:kOpenGrowlPreferencesTooltip];*/
statusItem = [[[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength] retain];
[statusItem setTarget: self];
[statusItem setAction: @selector (clickedStartStopTimer:)];
[statusItem setLength:NSVariableStatusItemLength];
NSBundle *bundle = [NSBundle mainBundle];
playItemImage = [[NSImage alloc] initWithContentsOfFile:[bundle pathForResource:@"playitem" ofType:@"png"]];
playItemHighlightImage = [[NSImage alloc] initWithContentsOfFile:[bundle pathForResource:@"playitem_hl" ofType:@"png"]];
stopItemImage = [[NSImage alloc] initWithContentsOfFile:[bundle pathForResource:@"stopitem" ofType:@"png"]];
stopItemHighlightImage = [[NSImage alloc] initWithContentsOfFile:[bundle pathForResource:@"stopitem_hl" ofType:@"png"]];
playToolImage = [[NSImage alloc] initWithContentsOfFile:[bundle pathForResource:@"playtool" ofType:@"png"]];
stopToolImage = [[NSImage alloc] initWithContentsOfFile:[bundle pathForResource:@"stoptool" ofType:@"png"]];
addTaskToolImage = [[NSImage alloc] initWithContentsOfFile:[bundle pathForResource:@"addtasktool" ofType:@"png"]];
addProjectToolImage = [[NSImage alloc] initWithContentsOfFile:[bundle pathForResource:@"addprojecttool" ofType:@"png"]];
dayToolImage = [[NSImage alloc] initWithContentsOfFile:[bundle pathForResource:@"daytool" ofType:@"png"]];
weekToolImage = [[NSImage alloc] initWithContentsOfFile:[bundle pathForResource:@"weektool" ofType:@"png"]];
monthToolImage = [[NSImage alloc] initWithContentsOfFile:[bundle pathForResource:@"monthtool" ofType:@"png"]];
dayToolImageUnsel = [[NSImage alloc] initWithContentsOfFile:[bundle pathForResource:@"dayofftool" ofType:@"png"]];
weekToolImageUnsel = [[NSImage alloc] initWithContentsOfFile:[bundle pathForResource:@"weekofftool" ofType:@"png"]];
monthToolImageUnsel = [[NSImage alloc] initWithContentsOfFile:[bundle pathForResource:@"monthofftool" ofType:@"png"]];
pickDateToolImage = [[NSImage alloc] initWithContentsOfFile:[bundle pathForResource:@"pickdatetool" ofType:@"png"]];
//[statusItem setMenu:m]; // retains m
[statusItem setToolTip:@"Time Tracker"];
[statusItem setHighlightMode:NO];
//[m release];
NSToolbar *toolbar = [[NSToolbar alloc] initWithIdentifier: @"TimeTrackerToolbar"];
[toolbar setDelegate: self];
[mainWindow setToolbar: toolbar];
[self updateStartStopState];
[self updateProminentDisplay];
[tvWorkPeriods setTarget: self];
[tvWorkPeriods setDoubleAction: @selector(doubleClickWorkPeriod:)];
NSMutableArray *descriptors = [NSMutableArray array];
[descriptors addObject:[[[NSSortDescriptor alloc] initWithKey:@"startTime" ascending:YES] autorelease]];
[descriptors addObject:[[[NSSortDescriptor alloc] initWithKey:@"parentTask.name" ascending:YES] autorelease]];
[workPeriodController setSortDescriptors:descriptors];
[tvProjects reloadData];
}
- (TWorkPeriod*) workPeriodAtIndex:(int) index
{
TWorkPeriod *wp = nil;
int result = [self selectedWorkPeriodRow];
TTask *task = [self taskForWorkTimeIndex:index timeIndex:&result];
wp = [[task workPeriods] objectAtIndex:result];
return wp;
}
- (TWorkPeriod*) selectedWorkPeriod
{
return [[workPeriodController arrangedObjects] objectAtIndex:[tvWorkPeriods selectedRow]];
}
- (IBAction)okClicked:(id) sender
{
[NSApp endSheet:panelEditWorkPeriod returnCode:NSOKButton];
}
- (IBAction)cancelClicked:(id) sender
{
[NSApp endSheet:panelEditWorkPeriod returnCode:NSCancelButton];
}
- (void)sheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
{
if (sheet == panelPickFilterDate) {
if (returnCode == NSOKButton) {
[_tbPickDateItem setLabel:[_dateFormatter stringFromDate:_selectedfilterDate]];
} else {
[self setFilterMode: FILTER_MODE_NONE];
[_tbPickDateItem setLabel:@"Pick Date"];
}
[self invalidateFilterPredicate];
[self applyFilter];
} else {
if (returnCode == NSOKButton) {
[self clickedChangeWorkPeriod: nil];
}
}
// hide the window
[sheet orderOut:nil];
}
- (void)notificationDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
{
[self invalidateFilterPredicate];
[self applyFilter];
// hide the window
[sheet orderOut:nil];
}
- (void) doubleClickWorkPeriod: (id) sender
{
// assert _selProject != nil
// assert _selTask != nil
TWorkPeriod *wp = [self selectedWorkPeriod];
[dtpEditWorkPeriodStartTime setDateValue: [wp startTime]];
[dtpEditWorkPeriodEndTime setDateValue: [wp endTime]];
[dtpEditWorkPeriodComment setString: [[wp comment] string]];
// [changeProjectController setSelectionIndex:[_projects indexOfObject:[[wp parentTask] parentProject]]];
[self provideProjectsForEditWpDialog:[[wp parentTask] parentProject]];
[self provideTasksForEditWpDialog:[[wp parentTask] parentProject]];
[_taskPopupButton selectItemWithTitle:[[wp parentTask] name]];
/* [panelEditWorkPeriod makeKeyAndOrderFront: self];
[NSApp runModalForWindow: panelEditWorkPeriod];
*/
[NSApp beginSheet:panelEditWorkPeriod modalForWindow:mainWindow modalDelegate:self
didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:) contextInfo:nil];
}
- (void) moveWorkPeriodToNewTask:(TWorkPeriod*) wp task:(TTask*) newParent
{
// first remove the workperiod from the old parent
TTask *oldParent = [wp parentTask];
[oldParent removeWorkPeriod:wp];
[newParent addWorkPeriod:wp];
}
- (IBAction)clickedChangeWorkPeriod:(id)sender
{
// assert _selProject != nil
// assert _selTask != nil
TWorkPeriod *wp = [self selectedWorkPeriod];
[wp setStartTime: [dtpEditWorkPeriodStartTime dateValue]];
[wp setEndTime: [dtpEditWorkPeriodEndTime dateValue]];
[wp setComment: [[[NSAttributedString alloc] initWithString:[dtpEditWorkPeriodComment string]] autorelease]];
// move the workperiod to a different task / project
if ([_taskPopupButton indexOfSelectedItem] > 0) {
int projectIndex = [_projectPopupButton indexOfSelectedItem];
TProject *selectedProject = [_projects objectAtIndex:projectIndex];
int taskIndex = [_taskPopupButton indexOfSelectedItem] - 1;
TTask *selectedTask = [[selectedProject tasks] objectAtIndex:taskIndex];
[self moveWorkPeriodToNewTask:wp task:selectedTask];
}
[_selTask updateTotalTime];
[_selProject updateTotalTime];
[tvProjects reloadData];
[tvTasks reloadData];
[self reloadWorkPeriods];
[NSApp stopModal];
[panelEditWorkPeriod orderOut: self];
}
- (void) showIdleNotification
{
[NSApp beginSheet:panelIdleNotification modalForWindow:mainWindow modalDelegate:self
didEndSelector:@selector(notificationDidEnd:returnCode:contextInfo:) contextInfo:nil];
/*
[NSApp activateIgnoringOtherApps: YES];
[NSApp runModalForWindow: panelIdleNotification];
[panelIdleNotification orderOut: self];*/
}
- (void) timerFunc: (NSTimer *) atimer
{
if ([panelIdleNotification isVisible]) {
return;
}
// assert timer != nil
// assert timer == atimer
if (timer != atimer) return;
// determine if the computer was on standby
NSDate *lastEndTime = [_curWorkPeriod endTime];
NSDate *curTime = [NSDate date];
if (_enableStandbyDetection && [curTime timeIntervalSinceDate:lastEndTime] > 60) {
[timer setFireDate: [NSDate distantFuture]];
// time jumped by 60 seconds, probably the computer was on standby
[_lastNonIdleTime release];
_lastNonIdleTime = [lastEndTime retain];
[self showIdleNotification];
return;
}
[_curWorkPeriod setEndTime: curTime];
[_curTask updateTotalTime];
[_curProject updateTotalTime];
[tvProjects reloadData];
[tvTasks reloadData];
[tvWorkPeriods reloadData];
int idleTime = [self idleTime];
if (idleTime == 0) {
[_lastNonIdleTime release];
_lastNonIdleTime = [[NSDate date] retain];
}
if (idleTime > _idleTimeoutSeconds) {
[timer setFireDate: [NSDate distantFuture]];
[self showIdleNotification];
}
[self updateProminentDisplay];
if (timeSinceSave > 5 * 60) {
[self saveData];
} else {
timeSinceSave++;
}
}
- (void)windowWillClose:(NSNotification *)notification
{
if ([notification object] == mainWindow)
[NSApp terminate: self];
if ([notification object] == panelEditWorkPeriod)
[NSApp stopModal];
}
- (NSString *) pathForDataFile : (bool) createIfNecessary
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *folder = @"~/Library/Application Support/TimeTracker/";
folder = [folder stringByExpandingTildeInPath];
if ([fileManager fileExistsAtPath: folder] == NO) {
[fileManager createDirectoryAtPath: folder attributes: nil];
}
NSString *fileName = @"data.plist";
return [folder stringByAppendingPathComponent: fileName];
}
- (NSString *) pathForDataFile
{
return [self pathForDataFile: YES];
}
- (bool) dataFileExists
{
NSFileManager *fm = [NSFileManager defaultManager];
NSString *dataFile = [self pathForDataFile:NO];
return [fm fileExistsAtPath:dataFile];
}
- (NSString*)serializeData
{
NSMutableString *result = [NSMutableString stringWithString:@"\"Project\";\"Task\";\"Date\";\"Start\";\"End\";\"Duration\";\"Comment\"\n"];
NSEnumerator *enumerator = [_projects objectEnumerator];
id anObject;
while (anObject = [enumerator nextObject])
{
[result appendString:[anObject serializeData:[self csvSeparatorChar]]];
}
return result;
}
- (void)saveData
{
NSData *theData=[NSKeyedArchiver archivedDataWithRootObject:_projects];
NSString * path = [self pathForDataFile];
NSMutableDictionary * rootObject;
rootObject = [NSMutableDictionary dictionary];
int count = [_lruTasks count];
NSMutableData *lruData = [[NSMutableData alloc] initWithCapacity:count * sizeof(int)];
[lruData setLength:count * sizeof(int)];
int* ptrData = (int*) [lruData mutableBytes];
NSEnumerator *enumLruTasks = [_lruTasks objectEnumerator];
TTask *task = nil;
while ((task = [enumLruTasks nextObject]) != nil) {
*ptrData = NSSwapHostIntToBig([task taskId]);
ptrData++;
}
[rootObject setValue:lruData forKey:@"lruIndexes"];
[rootObject setObject:theData forKey:@"ProjectTimes"];
[rootObject setValue:_autosaveCsvFilename forKey:@"autosaveCsvFilename"];
[rootObject setValue:_csvSeparatorChar forKey:@"separator"];
[rootObject setValue:[NSString stringWithFormat:@"%d", _maxLruSize] forKey:@"lruEntryCount"];
[rootObject setValue:[NSString stringWithFormat:@"%d", _idleTimeoutSeconds] forKey:@"idleTimeout"];
if (_autosaveCsv) {
[rootObject setValue:@"YES" forKey:@"autosave"];
} else {
[rootObject setValue:@"NO" forKey:@"autosave"];
}
if (_showTimeInMenuBar) {
[rootObject setValue:@"YES" forKey:@"showTimeInMenuBar"];
} else {
[rootObject setValue:@"NO" forKey:@"showTimeInMenuBar"];
}
if (_enableStandbyDetection) {
[rootObject setValue:@"YES" forKey:@"standbyDetection"];
} else {
[rootObject setValue:@"NO" forKey:@"standbyDetection"];
}
[NSKeyedArchiver archiveRootObject: rootObject toFile: path];
timeSinceSave = 0;
if (_autosaveCsv && _autosaveCsvFilename != nil) {
NSString *data = [self serializeData];
[data writeToFile:_autosaveCsvFilename atomically:YES];
}
}
- (IBAction)actionExport:(id)sender
{
NSSavePanel *sp;
int savePanelResult;
sp = [NSSavePanel savePanel];
[sp setTitle:@"Export"];
[sp setNameFieldLabel:@"Export to:"];
[sp setPrompt:@"Export"];
[sp setRequiredFileType:@"csv"];
savePanelResult = [sp runModalForDirectory:nil file:@"Time Tracker Data.csv"];
if (savePanelResult == NSOKButton) {
NSString *data = [self serializeData];
[data writeToFile:[sp filename] atomically:YES];
// [data release];
}
}
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
{
if (timer != nil)
[self stopTimer];
[self saveData];
NSLog(@"exiting app...........");
return NSTerminateNow;
}
- (void)tableView:(NSTableView *)aTableView willDisplayCell:(id)aCell forTableColumn:(NSTableColumn *)aTableColumn row:(unsigned)rowIndex {
if (_normalCol == nil) {
_normalCol = [[aCell textColor] retain];
_highlightCol = [[_normalCol highlightWithLevel:0.5] retain];
}
if (aTableView != tvWorkPeriods) {
return;
}
TWorkPeriod *wp = [[workPeriodController arrangedObjects] objectAtIndex:rowIndex];
// if we are showing the current task, apply different text color
if (wp == _curWorkPeriod) {
[aCell setTextColor:_highlightCol];
}
else {
[aCell setTextColor:_normalCol];
}
}
- (int)numberOfRowsInTableView:(NSTableView *)tableView
{
if (tableView == tvProjects) {
return [_projects count] + 1;
}
if (tableView == tvTasks) {
if (_selProject == nil)
return 0;
else if (ONLY_NON_NULL_TASKS_FOR_OVERVIEW) {
if (_selProject == _metaProject && _filteredTasks != nil) {
return [_filteredTasks count] + 1;
}
}
return [[_selProject tasks] count] + 1;
}
if (tableView == tvWorkPeriods) {
if (_selTask == nil)
return 0;
else
return [[_selTask workPeriods] count];
}
return 0;
}
- (TTask*) taskForWorkTimeIndex: (int) rowIndex timeIndex:(int*)resultIndex {
NSEnumerator *enumerator = [[_selProject tasks] objectEnumerator];
id aTask;
*resultIndex = rowIndex;
while (aTask = [enumerator nextObject])
{
int count = [[aTask workPeriods] count];
if (count > *resultIndex) {
break;
}
*resultIndex -= count;
}
return aTask;
}
- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)rowIndex
{
if (tableView == tvProjects) {
id project = nil;
if (rowIndex == 0) {
project = _metaProject;
} else {
project = [_projects objectAtIndex: rowIndex - 1];
}
if ([[tableColumn identifier] isEqualToString: @"ProjectName"]) {
return [project name];
}
if ([[tableColumn identifier] isEqualToString: @"TotalTime"]) {
return [TimeIntervalFormatter secondsToString: [project filteredTime:[self filterPredicate]]];
}
}
if (tableView == tvTasks) {
id<ITask> task = nil;
if (rowIndex == 0) {
task = _metaTask;
} else if (ONLY_NON_NULL_TASKS_FOR_OVERVIEW
&& _selProject == _metaProject && _filteredTasks != nil) {
task = [_filteredTasks objectAtIndex: rowIndex - 1];
} else {
task = [[_selProject tasks] objectAtIndex: rowIndex - 1];
}
if ([[tableColumn identifier] isEqualToString: @"TaskName"]) {
if (_selProject == _metaProject && rowIndex > 0) {
NSMutableString *name = [NSMutableString stringWithFormat:@"%@ (%@)", [task name], [[((TTask*)task) parentProject] name]];
return name;
}
return [task name];
}
if ([[tableColumn identifier] isEqualToString: @"TotalTime"]) {
return [TimeIntervalFormatter secondsToString: [task filteredTime:[self filterPredicate]]];
}
}
/*
if (tableView == tvWorkPeriods) {
TWorkPeriod *period = nil;
// find out which task contains the correct period
if (_selProject == nil)
// should not happen
return nil;
int workIndex = rowIndex;
id aTask;
aTask = [self taskForWorkTimeIndex:rowIndex timeIndex:&workIndex];