2 Copyright (C) 2005 SKYRIX Software AG
4 This file is part of SOPE.
6 SOPE is free software; you can redistribute it and/or modify it under
7 the terms of the GNU Lesser General Public License as published by the
8 Free Software Foundation; either version 2, or (at your option) any
11 SOPE is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
14 License for more details.
16 You should have received a copy of the GNU Lesser General Public
17 License along with SOPE; see the file COPYING. If not, write to the
18 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
22 #include "NSCalendarDate+misc.h"
25 @implementation NSCalendarDate(CalMatrix)
27 static BOOL debugCalMatrix = NO;
29 - (NSArray *)calendarMatrixWithStartDayOfWeek:(short)_caldow
30 onlyCurrentMonth:(BOOL)_onlyThisMonth
32 // Note: we keep clock time!
33 NSAutoreleasePool *pool;
34 NSCalendarDate *firstInMonth;
36 NSArray *weeks[8] = { nil, nil, nil, nil, nil, nil, nil, nil };
37 NSCalendarDate *week[8] = { nil, nil, nil, nil, nil, nil, nil, nil };
38 unsigned firstDoW, numDaysInLastMonth, i, j, curday, curweek, curmonth;
40 /* all the date operations use autorelease, so we wrap it in a pool */
41 pool = [[NSAutoreleasePool alloc] init];
44 NSLog(@"calmatrix for: %@", self);
46 firstInMonth = [[self firstDayOfMonth] beginOfDay];
47 firstDoW = [firstInMonth dayOfWeek];
48 curmonth = [firstInMonth monthOfYear];
50 numDaysInLastMonth = (firstDoW < _caldow)
51 ? (firstDoW + 7 - _caldow)
52 : (firstDoW - _caldow);
55 NSLog(@" LAST: %d FIRST-DOW: %d START-DOW: %d",
56 numDaysInLastMonth, firstDoW, _caldow);
63 j = 0; /* this is the position where first week days are added */
66 /* add dates from last month */
67 for (i = numDaysInLastMonth; i > 0; i--) {
68 week[numDaysInLastMonth - i] =
69 [firstInMonth dateByAddingYears:0 months:0 days:-i];
71 j = numDaysInLastMonth;
73 week[j] = firstInMonth; j++;
75 for (i = numDaysInLastMonth + 1; i < 7; i++, j++) {
76 week[j] = [firstInMonth dateByAddingYears:0 months:0
77 days:(i - numDaysInLastMonth)];
79 curday = 7 - numDaysInLastMonth;
82 NSLog(@" current day after 1st week: %d, week: %d", curday, curweek);
84 /* finish first week */
85 weeks[0] = [[NSArray alloc] initWithObjects:week count:j];
91 BOOL foundNewMonth = NO;
93 for (i = 0; i < 7; i++, curday++) {
94 week[i] = [firstInMonth dateByAddingYears:0 months:0 days:curday];
96 if (!foundNewMonth && curday > 27) {
97 foundNewMonth = ([week[i] monthOfYear] != curmonth) ? YES : NO;
98 if (foundNewMonth && _onlyThisMonth)
104 weeks[curweek] = [[NSArray alloc] initWithObjects:week count:i];
112 /* build final matrix */
114 matrix = [[NSArray alloc] initWithObjects:weeks count:curweek];
115 for (i = 0; i < 8; i++) {
121 NSLog(@"matrix for %@: %@", self, matrix);
124 return [matrix autorelease];
127 @end /* NSCalendarDate(CalMatrix) */