forked from Fusion/Journler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Calendar.m
1700 lines (1269 loc) · 49.7 KB
/
Calendar.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
/*
Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the
distribution.
* Neither the name of the author nor the names of its contributors may be used to endorse or
promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Basically, you can use the code in your free, commercial, private and public projects
// as long as you include the above notice and attribute the code to Philip Dow / Sprouted
// If you use this code in an app send me a note. I'd love to know how the code is used.
// Please also note that this copyright does not supersede any other copyrights applicable to
// open source code used herein. While explicit credit has been given in the Journler about box,
// it may be lacking in some instances in the source code. I will remedy this in future commits,
// and if you notice any please point them out.
#import "Calendar.h"
#import "Definitions.h"
#import "JournlerApplicationDelegate.h"
#import "DatesController.h"
#import "JournlerEntry.h"
#import "JournlerJournal.h"
#import "NSAlert+JournlerAdditions.h"
#import "MonthAndYearCell.h"
#import "CalendarButtonCell.h"
#import <SproutedInterface/SproutedInterface.h>
#define kRowHeight 18
#define kColWidth 22
#define kButtonCellHeight 16
#define kWidthOffset 2
#define kCalendarRequiredWidth 160
#define kMonthYearOffset 23
#define kBackgroundOffset 58
#define kDaysOffset 57
#define kDayHeaderOffset 40
#pragma mark -
@implementation Calendar
static void SetSegmentDescriptions(NSSegmentedControl *control, NSString *firstDescription, ...) {
// Use NSAccessibilityUnignoredDescendant to be sure we start with the correct object.
id segmentElement = NSAccessibilityUnignoredDescendant(control);
// Use the accessibility protocol to get the children.
NSArray *segments = [segmentElement accessibilityAttributeValue:NSAccessibilityChildrenAttribute];
va_list args;
va_start(args, firstDescription);
NSString *description = firstDescription;
for ( id segment in segments ) {
if (description != nil) {
[segment accessibilitySetOverrideValue:description forAttribute:NSAccessibilityDescriptionAttribute];
} else {
// Exit loop if we run out of descriptions.
break;
}
description = va_arg(args, id);
}
va_end(args);
}
#pragma mark -
+ (void)initialize
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[self exposeBinding:@"content"];
[pool release];
}
- (id)initWithFrame:(NSRect)frameRect
{
if ( self = [super initWithFrame:frameRect] ) {
//
// initial date information
todaysDate = [[NSCalendarDate calendarDate] retain];
selectedDate = [[NSCalendarDate calendarDate] retain];
myDay = [selectedDate dayOfMonth];
myMonth = [selectedDate monthOfYear];
myYear = [selectedDate yearOfCommonEra];
//set up a timer to catch the day change
NSCalendarDate *daychangeFireDate = [[NSCalendarDate dateWithYear:[todaysDate yearOfCommonEra]
month:[todaysDate monthOfYear] day:[todaysDate dayOfMonth] hour:0 minute:0 second:1 timeZone:nil]
dateByAddingYears:0 months:0 days:1 hours:0 minutes:0 seconds:0];
dateWatcher = [[NSTimer alloc] initWithFireDate:daychangeFireDate interval:86400
target:self selector:@selector(resetToday:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:dateWatcher forMode:NSDefaultRunLoopMode];
//and cursor
pointCursor = [[NSCursor pointingHandCursor] retain];
// wake from sleep notification - the date may have changed
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(computerDidWake:)
name:PDPowerManagementNotification
object:[PDPowerManagement sharedPowerManagement]];
drawsBorder = NO;
backgroundColor = [[NSColor whiteColor] retain];
content = nil;
_dropDate = -1;
[self registerForDraggedTypes:[NSArray arrayWithObjects:PDEntryIDPboardType,
NSFilenamesPboardType, NSURLPboardType, NSRTFDPboardType, NSRTFPboardType,
NSStringPboardType, NSTIFFPboardType, NSPICTPboardType, kMailMessagePboardType, nil]];
monthYearCell = [[MonthAndYearCell alloc] init];
monthBackCell = [[CalendarButtonCell alloc] init];
monthTodayCell = [[CalendarButtonCell alloc] init];
monthForwardCell = [[CalendarButtonCell alloc] init];
[monthBackCell setTarget:self];
[monthBackCell setAction:@selector(monthToLeft:)];
[monthBackCell setCommand:kCalendarCommandMonthBack];
[monthBackCell setContinuous:YES];
[monthBackCell setPeriodicDelay:0.8 interval:0.2];
[monthTodayCell setTarget:self];
[monthTodayCell setAction:@selector(toToday:)];
[monthTodayCell setCommand:kCalendarCommandToToday];
[monthTodayCell setContinuous:YES];
[monthTodayCell setPeriodicDelay:0.8 interval:500];
[monthForwardCell setTarget:self];
[monthForwardCell setAction:@selector(monthToRight:)];
[monthForwardCell setCommand:kCalendarCommandMonthForward];
[monthForwardCell setContinuous:YES];
[monthForwardCell setPeriodicDelay:0.8 interval:0.2];
// register for a notification prefs will send when th start day changes
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(startDayChanged:)
name:CalendarStartDayChangedNotification
object:nil];
currentDragRect = NSZeroRect;
}
return self;
}
- (void) dealloc
{
#ifdef __DEBUG__
NSLog(@"%s",__PRETTY_FUNCTION__);
#endif
[[NSNotificationCenter defaultCenter] removeObserver:self];
[self unregisterDraggedTypes];
[selectedDate release];
[todaysDate release];
[pointCursor release];
[backgroundColor release];
[monthYearCell release];
[monthBackCell release];
[monthTodayCell release];
[monthForwardCell release];
[super dealloc];
}
- (void) ownerWillClose:(NSNotification*)aNotification
{
[dateWatcher invalidate];
[dateWatcher release];
}
#pragma mark -
+ (NSArray*) englishWeekDays {
return [NSArray arrayWithObjects:@"Sunday", @"Monday", @"Tuesday", @"Wednesday",
@"Thursday", @"Friday", @"Saturday", nil];
}
+ (NSInteger) lastDayOfMonth:(NSInteger)month year:(NSInteger)year {
//0 is january, 11 is december
//even though locally (myMonth) 1 is january and 12 is december
BOOL leap = NO;
static NSInteger daysInMonth[] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
if ( year % 4 == 0 ) {
leap = YES;
if ( year % 100 == 0 ) { leap = NO; }
if ( year % 400 == 0 ) { leap = YES; }
}
if ( leap && month == 2 ) { return 29; }
else { return daysInMonth[month-1]; }
}
#pragma mark -
- (id) delegate
{
return delegate;
}
- (void) setDelegate:(id)anObject
{
delegate = anObject;
}
- (NSArray*) content
{
return content;
}
- (void) setContent:(NSArray*)anArray
{
if ( content != anArray )
{
[content release];
content = [anArray retain];
[self updateDaysWithEntries];
}
}
- (BOOL) highlighted
{
return highlighted;
}
- (void) setHighlighted:(BOOL)highlight
{
highlighted = highlight;
}
- (BOOL) drawsBorder
{
return drawsBorder;
}
- (void) setDrawsBorder:(BOOL)draw
{
drawsBorder = draw;
}
- (NSColor*) backgroundColor
{
return backgroundColor;
}
- (void) setBackgroundColor:(NSColor*)bgColor
{
if ( backgroundColor != bgColor )
{
[backgroundColor release];
backgroundColor = [bgColor copyWithZone:[self zone]];
}
}
- (DatesController*) dataSource
{
return dataSource;
}
- (void) setDataSource:(DatesController*)aController
{
if ( dataSource != aController )
{
[dataSource release];
dataSource = [aController retain];
}
}
#pragma mark -
- (void)setSelectedDate:(NSDate*)aDate
{
BOOL entireDisplayNeedsUpdate = YES;
NSRect earlierInvalidatedRect = [self frameOfDateWithDay:myDay month:myMonth year:myYear];
if ( aDate == nil ) // date shouldn't be nil
aDate = [NSCalendarDate calendarDate];
// else if ( [aDate isMemberOfClass:[NSDate class]] )
// leopard bug, must guarantee that this is a calendar date
else
aDate = [aDate dateWithCalendarFormat:nil timeZone:nil];
if ( selectedDate != aDate ) {
[selectedDate release];
selectedDate = [aDate copyWithZone:[self zone]];
}
//and update our date integers for easy access
NSInteger newYear = [(NSCalendarDate*)selectedDate yearOfCommonEra];
NSInteger newMonth = [(NSCalendarDate*)selectedDate monthOfYear];
if ( myMonth == newMonth && myYear == newYear )
entireDisplayNeedsUpdate = NO;
myDay = [(NSCalendarDate*)selectedDate dayOfMonth];
myMonth = newMonth;
myYear = newYear;
//if ( entireDisplayNeedsUpdate )
[self updateDaysWithEntries];
[[self window] invalidateCursorRectsForView:self];
if ( entireDisplayNeedsUpdate )
[self setNeedsDisplay:YES];
else
{
NSRect invalidatedRect = [self frameOfDateWithDay:myDay month:myMonth year:myYear];
[self setNeedsDisplayInRect:invalidatedRect];
[self setNeedsDisplayInRect:earlierInvalidatedRect];
}
}
- (NSCalendarDate*) selectedDate {
// return a mix of the current date and the present time
NSCalendarDate *now = [NSCalendarDate calendarDate];
return [NSCalendarDate
dateWithYear:[selectedDate yearOfCommonEra] month:[selectedDate monthOfYear] day:[selectedDate dayOfMonth]
hour:[now hourOfDay] minute:[now minuteOfHour] second:[now secondOfMinute] timeZone:nil];
}
- (void) setCurrentDate:(NSCalendarDate*)aDate
{
[self setSelectedDate:aDate];
}
- (NSCalendarDate*) currentDate
{
return [self selectedDate];
}
#pragma mark -
- (void) resetToday:(id)sender {
//called by the timer every 24 hours 1 second after midnight to update the current day
//reset "todays" date
[todaysDate release];
todaysDate = [[NSCalendarDate calendarDate] retain];
//update our display
//[self setNeedsDisplay:YES];
[self setNeedsDisplayInRect:[self frameOfDateWithDay:[todaysDate dayOfWeek] month:[todaysDate monthOfYear] year:[todaysDate yearOfCommonEra]]];
}
- (void) computerDidWake:(NSNotification*)aNotification {
// just make sure that today's date is corrected if the computer was asleep during a midnight date change
if ( [[[aNotification userInfo] objectForKey:PDPowerManagementMessage] integerValue] == PDPowerManagementPoweredOn )
[self resetToday:self];
}
#pragma mark -
- (void)dayToLeft {
BOOL entireDisplayNeedsUpdate = NO;
NSRect earlierInvalidatedRect = [self frameOfDateWithDay:myDay month:myMonth year:myYear];
myDay--;
if ( myDay < 1 ) {
//get us set up on the right day
if ( myMonth == 1 ) { myDay = [Calendar lastDayOfMonth:12 year:myYear]; }
else { myDay = [Calendar lastDayOfMonth:myMonth-1 year:myYear]; }
//and shift our month, which will take care of refreshing
[self monthToLeft];
entireDisplayNeedsUpdate = YES;
}
else {
//call a setCurrentInfo so our latest information is posted to our observers.
[self setSelectedDate:[NSCalendarDate dateWithYear:myYear month:myMonth day:myDay hour:1 minute:1 second:1 timeZone:nil]];
}
if ( entireDisplayNeedsUpdate )
[self setNeedsDisplay:YES];
else
{
NSRect invalidatedRect = [self frameOfDateWithDay:myDay month:myMonth year:myYear];
[self setNeedsDisplayInRect:invalidatedRect];
[self setNeedsDisplayInRect:earlierInvalidatedRect];
}
}
- (void)dayToRight
{
BOOL entireDisplayNeedsUpdate = NO;
NSRect earlierInvalidatedRect = [self frameOfDateWithDay:myDay month:myMonth year:myYear];
myDay++;
if ( myDay > [Calendar lastDayOfMonth:myMonth year:myYear] ) {
myDay = 1;
[self monthToRight];
entireDisplayNeedsUpdate = YES;
}
else {
//call a setCurrentInfo so our latest information is posted to our observers.
[self setSelectedDate:[NSCalendarDate dateWithYear:myYear month:myMonth day:myDay hour:1 minute:1 second:1 timeZone:nil]];
}
if ( entireDisplayNeedsUpdate )
[self setNeedsDisplay:YES];
else
{
NSRect invalidatedRect = [self frameOfDateWithDay:myDay month:myMonth year:myYear];
[self setNeedsDisplayInRect:invalidatedRect];
[self setNeedsDisplayInRect:earlierInvalidatedRect];
}
}
- (void) monthToLeft
{
BOOL entireDisplayNeedsUpdate = YES;
NSRect earlierInvalidatedRect = [self frameOfDateWithDay:myDay month:myMonth year:myYear];
if ( myMonth != 1 ) { myMonth--; }
else {
myMonth = 12;
myYear--;
}
//and in case we've switched months and our day has gone over
if ( myDay > [Calendar lastDayOfMonth:myMonth year:myYear] ) { myDay = [Calendar lastDayOfMonth:myMonth year:myYear]; }
//call a setCurrentInfo so our latest information is posted to our observers.
[self setSelectedDate:[NSCalendarDate dateWithYear:myYear month:myMonth day:myDay hour:1 minute:1 second:1 timeZone:nil]];
if ( entireDisplayNeedsUpdate )
[self setNeedsDisplay:YES];
else
{
NSRect invalidatedRect = [self frameOfDateWithDay:myDay month:myMonth year:myYear];
[self setNeedsDisplayInRect:invalidatedRect];
[self setNeedsDisplayInRect:earlierInvalidatedRect];
}
}
- (void) monthToRight
{
BOOL entireDisplayNeedsUpdate = YES;
NSRect earlierInvalidatedRect = [self frameOfDateWithDay:myDay month:myMonth year:myYear];
if ( myMonth != 12 ) { myMonth++; }
else {
myMonth = 1;
myYear++;
}
//and in case we've switched months and our day has gone over
if ( myDay > [Calendar lastDayOfMonth:myMonth year:myYear] ) { myDay = [Calendar lastDayOfMonth:myMonth year:myYear]; }
//call a setCurrentInfo so our latest information is posted to our observers.
[self setSelectedDate:[NSCalendarDate dateWithYear:myYear month:myMonth day:myDay hour:1 minute:1 second:1 timeZone:nil]];
if ( entireDisplayNeedsUpdate )
[self setNeedsDisplay:YES];
else
{
NSRect invalidatedRect = [self frameOfDateWithDay:myDay month:myMonth year:myYear];
[self setNeedsDisplayInRect:invalidatedRect];
[self setNeedsDisplayInRect:earlierInvalidatedRect];
}
}
- (void) toToday
{
BOOL entireDisplayNeedsUpdate = NO;
NSRect earlierInvalidatedRect = [self frameOfDateWithDay:myDay month:myMonth year:myYear];
if ( ![[[NSCalendarDate calendarDate] descriptionWithCalendarFormat:@"%Y%m%d"] isEqualToString:
[todaysDate descriptionWithCalendarFormat:@"%Y%m%d"]] )
[self resetToday:self];
[self setSelectedDate:[NSCalendarDate calendarDate]];
if ( entireDisplayNeedsUpdate )
[self setNeedsDisplay:YES];
else
{
NSRect invalidatedRect = [self frameOfDateWithDay:myDay month:myMonth year:myYear];
[self setNeedsDisplayInRect:invalidatedRect];
[self setNeedsDisplayInRect:earlierInvalidatedRect];
}
}
#pragma mark -
- (IBAction) dayToLeft:(id)sender {
[self dayToLeft];
}
- (IBAction) dayToRight:(id)sender {
[self dayToRight];
}
- (IBAction) monthToLeft:(id)sender {
[self monthToLeft];
}
- (IBAction) monthToRight:(id)sender {
[self monthToRight];
}
- (IBAction) toToday:(id)sender {
[self toToday];
}
#pragma mark -
- (IBAction) contexutalDateChange:(id)sender {
if ( [sender tag] >= 501 && [sender tag] <= 512 ) {
// acquire a month from 01 to 12 for January to February
NSInteger targetMonth = [sender tag] - 500;
NSInteger highestDay = [Calendar lastDayOfMonth:targetMonth year:myYear];
NSCalendarDate *newDate = [NSCalendarDate dateWithYear:myYear month:targetMonth day:(myDay<=highestDay?myDay:highestDay)
hour:0 minute:0 second:0 timeZone:nil];
[self setSelectedDate:newDate];
}
else if ( [sender tag] == 400 ) {
// requesting a year change
NSInteger newYear = [sender integerValue];
NSInteger highestDay = [Calendar lastDayOfMonth:myMonth year:newYear];
NSCalendarDate *newDate = [NSCalendarDate dateWithYear:newYear month:myMonth day:(myDay<=highestDay?myDay:highestDay)
hour:0 minute:0 second:0 timeZone:nil];
[self setSelectedDate:newDate];
}
else if ( [sender tag] == 401 ) {
// focus on the year field and select it
//[[self window] makeFirstResponder:yearField];
//[yearField selectText:self];
}
}
- (BOOL)validateMenuItem:(NSMenuItem*)anItem {
BOOL enabled = YES;
if ( [anItem tag] >= 501 && [anItem tag] <= 512 ) {
// acquire a month from 01 to 12 for January to February
NSInteger targetMonth = [anItem tag] - 500;
if ( targetMonth == myMonth )
[anItem setState:NSOnState];
else
[anItem setState:NSOffState];
}
return enabled;
}
#pragma mark -
- (NSString*) todaysInfo:(NSString*)format {
//always create this thing on the fly as I don't keep this information in memory - localizedDateInfo ?
return [[NSCalendarDate dateWithYear:myYear month:myMonth day:myDay hour:1 minute:1 second:1 timeZone:nil] descriptionWithCalendarFormat:format locale:nil];
}
// ============================================================
// Handling our display
// ============================================================
#pragma mark -
#pragma mark Drawing
- (void)drawRect:(NSRect)rect {
//NSLog(@"calendar content count: %i",[content count]);
NSString *dayID;
NSMutableDictionary *tempAttributes = [NSMutableDictionary dictionary];
NSRect bds = [self bounds];
NSInteger total_offset = kWidthOffset + ( bds.size.width/2 - kCalendarRequiredWidth/2 );
[backgroundColor set];
NSRectFill(bds);
if ( drawsBorder ) {
[[NSColor lightGrayColor] set];
NSFrameRect(bds);
}
else
{
[[NSColor colorWithCalibratedWhite:0.5 alpha:1.0] set];
NSFrameRect( NSMakeRect(0,bds.size.height-1,bds.size.width,bds.size.height-1) );
//[[NSBezierPath bezierPathWithLineFrom:NSMakePoint(0,bds.size.height-1) to:NSMakePoint(bds.size.width,bds.size.height-1) lineWidth:1] stroke];
}
NSInteger col, row, offset, i;
//draw my days
[tempAttributes setObject:[NSFont boldSystemFontOfSize:11.0] forKey:NSFontAttributeName];
[tempAttributes setObject:[NSColor blackColor] forKey:NSForegroundColorAttributeName];
NSInteger start_day = [[NSUserDefaults standardUserDefaults] integerForKey:@"CalendarStartDay"];
// 0 indicates Sunday, 6 indicates Monday
NSInteger day_id = start_day;
NSArray *weekDays = [[NSUserDefaults standardUserDefaults] objectForKey:NSShortWeekDayNameArray];
if ( !weekDays || [weekDays count] < 7 ) weekDays = [Calendar englishWeekDays];
for ( i = 0; i <= 6 ; i++ ) {
dayID = [[weekDays objectAtIndex:day_id] substringToIndex:1];
[dayID drawAtPoint:
NSMakePoint( total_offset + kColWidth*i + ( kColWidth/2 - [dayID sizeWithAttributes:tempAttributes].width/2 ),
kDayHeaderOffset) withAttributes:tempAttributes];
day_id++;
if (day_id == 7 ) day_id = 0;
}
//reset the font info
NSFont *ohneEntriesFont = [NSFont systemFontOfSize:11.0];
NSFont *mitEntriesFont = [NSFont boldSystemFontOfSize:11.0];
[tempAttributes setObject:ohneEntriesFont forKey:NSFontAttributeName];
// set up offset based on first day of week
offset = [[NSCalendarDate dateWithYear:myYear month:myMonth day:1 hour:1 minute:1 second:1 timeZone:nil] dayOfWeek];
// set the original column and row based on offset and start information
col = offset - start_day;
row = 0;
// if the original column due to offset is seven or more, adjust
if ( col < 0 ) col+= 7;
NSInteger todaysDay = [todaysDate dayOfMonth];
NSInteger todaysMonth = [todaysDate monthOfYear];
NSInteger todaysYear = [todaysDate yearOfCommonEra];
// draw the buttons
[self drawButtons];
// draw the month and year
[monthYearCell setSelectedMonth:myMonth-1];
[monthYearCell setSelectedYear:[[self selectedDate] yearOfCommonEra]];
[monthYearCell drawWithFrame:
NSMakeRect(total_offset, kMonthYearOffset, bds.size.width - total_offset*2, kRowHeight-2) inView:self];
// draw the background for the first row
NSBezierPath *bg = [NSBezierPath bezierPathWithRoundedRect:
NSMakeRect(total_offset, kBackgroundOffset, bds.size.width - total_offset*2, kRowHeight-2)
cornerRadius:8.0];
[[NSColor colorWithCalibratedWhite:0.95 alpha:1.0] set];
[bg fill];
// draw the days
for ( i = 1; i <= [Calendar lastDayOfMonth:myMonth year:myYear ]; i++ ) {
// create the string that will be drawn
dayID = [NSString stringWithFormat:@"%i",i];
// draw the row's background whenever the 0 columns is reached
if ( col == 0 && row != 0 ) {
NSBezierPath *bg = [NSBezierPath bezierPathWithRoundedRect:
NSMakeRect(total_offset, kBackgroundOffset+row*kRowHeight, bds.size.width - total_offset*2, kRowHeight-2)
cornerRadius:8.0];
[[NSColor colorWithCalibratedWhite:0.95 alpha:1.0] set];
[bg fill];
}
// draw a drop circle
if ( i == _dropDate ) {
// highlight the day grey
[[NSColor colorWithCalibratedWhite:0.4 alpha:1.0] set];
[[self bezierPathForSelectedDateAtColumn:col row:row offset:total_offset] fill];
// bold the date and use a white color
NSFont *font = [tempAttributes objectForKey:NSFontAttributeName];
NSFont *boldFont = [[NSFontManager sharedFontManager] convertFont:font toHaveTrait:NSBoldFontMask];
[tempAttributes setObject:boldFont forKey:NSFontAttributeName];
[tempAttributes setObject:[NSColor whiteColor] forKey:NSForegroundColorAttributeName];
// draw the date
[dayID drawAtPoint:NSMakePoint(
total_offset+col*kColWidth+( kColWidth/2 - [dayID sizeWithAttributes:tempAttributes].width/2 ),
kDaysOffset+row*kRowHeight + ( kRowHeight/2 - [dayID sizeWithAttributes:tempAttributes].height/2 ) )
withAttributes:tempAttributes];
// set the font back
[tempAttributes setObject:font forKey:NSFontAttributeName];
}
// draw the selected day
else if ( i == myDay ) {
// highlight the day blue
if (([[self window] firstResponder] == self) && [[self window] isMainWindow] && [[self window] isKeyWindow])
[[NSColor colorWithCalibratedRed:102.0/255.0 green:133.0/255.0 blue:183.0/255.0 alpha:1.0] set];
else
[[NSColor colorWithCalibratedRed:152.0/255.0 green:170.0/255.0 blue:196.0/255.0 alpha:0.9] set];
[[self bezierPathForSelectedDateAtColumn:col row:row offset:total_offset] fill];
// bold the date and use a white color
NSFont *font = [tempAttributes objectForKey:NSFontAttributeName];
NSFont *boldFont = [[NSFontManager sharedFontManager] convertFont:font toHaveTrait:NSBoldFontMask];
[tempAttributes setObject:boldFont forKey:NSFontAttributeName];
[tempAttributes setObject:[NSColor whiteColor] forKey:NSForegroundColorAttributeName];
// draw the date
[dayID drawAtPoint:NSMakePoint(
total_offset+col*kColWidth+( kColWidth/2 - [dayID sizeWithAttributes:tempAttributes].width/2 ),
kDaysOffset+row*kRowHeight + ( kRowHeight/2 - [dayID sizeWithAttributes:tempAttributes].height/2 ) )
withAttributes:tempAttributes];
// set the font back
[tempAttributes setObject:font forKey:NSFontAttributeName];
}
// draw todays day if it is other than the selected day
else if ( todaysDay == i && todaysMonth == myMonth && todaysYear == myYear ) {
// highlight the day grey
[[NSColor colorWithCalibratedWhite:0.7 alpha:1.0] set];
[[self bezierPathForSelectedDateAtColumn:col row:row offset:total_offset] fill];
// bold the date and use a white color
NSFont *font = [tempAttributes objectForKey:NSFontAttributeName];
NSFont *boldFont = [[NSFontManager sharedFontManager] convertFont:font toHaveTrait:NSBoldFontMask];
[tempAttributes setObject:boldFont forKey:NSFontAttributeName];
[tempAttributes setObject:[NSColor whiteColor] forKey:NSForegroundColorAttributeName];
// draw the date
[dayID drawAtPoint:NSMakePoint(
total_offset+col*kColWidth+( kColWidth/2 - [dayID sizeWithAttributes:tempAttributes].width/2 ),
kDaysOffset+row*kRowHeight + ( kRowHeight/2 - [dayID sizeWithAttributes:tempAttributes].height/2 ) )
withAttributes:tempAttributes];
// set the font back
[tempAttributes setObject:font forKey:NSFontAttributeName];
}
// draw a date neither selected or today
else
{
// color the date depending on the presence of entries
if ( dayOfMonthHasEntry[i] )
{
// date with entry
[tempAttributes setObject:mitEntriesFont forKey:NSFontAttributeName];
[tempAttributes setObject:[NSColor colorWithCalibratedWhite:0.15 alpha:1.0] forKey:NSForegroundColorAttributeName];
}
else
{
// date without entry
[tempAttributes setObject:ohneEntriesFont forKey:NSFontAttributeName];
[tempAttributes setObject:[NSColor darkGrayColor] forKey:NSForegroundColorAttributeName];
}
// draw the date
[dayID drawAtPoint:NSMakePoint(
total_offset+col*kColWidth+( kColWidth/2 - [dayID sizeWithAttributes:tempAttributes].width/2 ),
kDaysOffset+row*kRowHeight + ( kRowHeight/2 - [dayID sizeWithAttributes:tempAttributes].height/2 ) )
withAttributes:tempAttributes];
}
col++;
if ( col == 7 ) {
row++;
col = 0;
}
}
}
- (void) drawButtons {
NSRect bds = [self bounds];
NSInteger third = ceil(bds.size.width / 3.0);
NSRect monthBack = NSMakeRect(0,0,third,kButtonCellHeight);
NSRect monthToday = NSMakeRect(third,0,third,kButtonCellHeight);
NSRect monthForward = NSMakeRect(bds.size.width-third,0,third,kButtonCellHeight);
[monthBackCell drawWithFrame:monthBack inView:self];
[monthForwardCell drawWithFrame:monthForward inView:self];
[monthTodayCell drawWithFrame:monthToday inView:self];
}
- (NSBezierPath*) bezierPathForSelectedDateAtColumn:(NSInteger)column row:(NSInteger)row offset:(NSInteger)offset {
NSBezierPath *path;
if ( column == 0 ) {
// special action for a column at the far left
NSBezierPath *curve = [NSBezierPath bezierPathWithRoundedRect:
NSMakeRect(offset+column*kColWidth, kBackgroundOffset+row*kRowHeight, 22, kRowHeight-2)
cornerRadius:8.0];
path = [NSBezierPath bezierPathWithRect:
NSMakeRect(offset+12+column*kColWidth, kBackgroundOffset+row*kRowHeight, 10, kRowHeight-2)];
[path appendBezierPath:curve];
}
else if ( column == 6 ) {
// special action for a column at the far right
NSBezierPath *curve = [NSBezierPath bezierPathWithRoundedRect:
NSMakeRect(offset+2+column*kColWidth, kBackgroundOffset+row*kRowHeight, 22, kRowHeight-2)
cornerRadius:8.0];
path = [NSBezierPath bezierPathWithRect:
NSMakeRect(offset+column*kColWidth, kBackgroundOffset+row*kRowHeight, 10, kRowHeight-2)];
[path appendBezierPath:curve];
}
else {
// regular old rectangle
path = [NSBezierPath bezierPathWithRect:
NSMakeRect(offset+column*kColWidth, kBackgroundOffset+row*kRowHeight, 21, kRowHeight-2)];
}
return path;
}
- (NSRect) frameOfDateWithDay:(NSInteger)aDay month:(NSInteger)aMonth year:(NSInteger)aYear
{
if ( aMonth != myMonth || aYear != myYear )
return NSZeroRect;
else
{
NSInteger col, row, offset, i;
NSInteger start_day = [[NSUserDefaults standardUserDefaults] integerForKey:@"CalendarStartDay"];
NSRect bds = [self bounds];
NSInteger total_offset = kWidthOffset + ( bds.size.width/2 - kCalendarRequiredWidth/2 );
NSRect theFrame = NSZeroRect;
// set up offset based on first day of week
offset = [[NSCalendarDate dateWithYear:myYear month:myMonth day:1 hour:1 minute:1 second:1 timeZone:nil] dayOfWeek];
// set the original column and row based on offset and start information
col = offset - start_day;
row = 0;
// if the original column due to offset is seven or more, adjust
if ( col < 0 ) col+= 7;
// get the column and row for this position
for ( i = 1; i < aDay; i++ )
{
col++;
if ( col == 7 )
{
row++;
col = 0;
}
}
theFrame = NSMakeRect(total_offset+col*kColWidth - 2, kBackgroundOffset+row*kRowHeight - 2, kColWidth + 4, kRowHeight + 4);
return theFrame;
}
}
#pragma mark -
- (void)keyDown:(NSEvent *)theEvent {
//
// calendar as first responder, keyboard events change date
unichar key = [[theEvent charactersIgnoringModifiers] characterAtIndex:0];
NSUInteger flags = [theEvent modifierFlags];
if ( key == NSLeftArrowFunctionKey && !(flags & NSShiftKeyMask) )
[self dayToLeft];
else if ( key == NSLeftArrowFunctionKey && (flags & NSShiftKeyMask) )
[self monthToLeft];
else if ( key == NSRightArrowFunctionKey && !(flags & NSShiftKeyMask) )
[self dayToRight];
else if ( key == NSRightArrowFunctionKey && (flags & NSShiftKeyMask) )
[self monthToRight];
else if ( key == NSCarriageReturnCharacter || key == NSEnterCharacter )
[self toToday];
//else if ( key == NSTabCharacter )
// [self monthToRight];
//else if ( key == (unichar)25 ) // the capitalized tab?
// [self monthToLeft];
}
- (void)mouseDown:(NSEvent *)theEvent {
//
// calendar as first responder, mouse events change date
NSRect bds = [self bounds];
NSInteger total_offset = kWidthOffset + ( bds.size.width/2 - kCalendarRequiredWidth/2 );
NSInteger myX, myY, i, j, offset, dayHit;
NSPoint mouseLoc = [self convertPoint:[theEvent locationInWindow] fromView:nil];
// git rid of first responder so that the year field won't highlight ( fr goes away otherwise anyway? )
//[[self window] makeFirstResponder:nil];
NSRect navRect = NSMakeRect(0,0,bds.size.width,kButtonCellHeight);
NSRect monthYearRect = NSMakeRect(total_offset, kMonthYearOffset, bds.size.width - total_offset*2, kRowHeight-2);
// check to see if the user is clicking one of the buttons
if ( NSPointInRect(mouseLoc,navRect) ) {
NSInteger third = ceil(bds.size.width / 3.0);
NSRect monthBack = NSMakeRect(0,0,third,kButtonCellHeight);
NSRect monthToday = NSMakeRect(third,0,third,kButtonCellHeight);
NSRect monthForward = NSMakeRect(bds.size.width-third,0,third,kButtonCellHeight);