comctl32/monthcal: Use recently introduced enum in scroll buttons painting helper.
[wine] / dlls / comctl32 / monthcal.c
1 /*
2  * Month calendar control
3  *
4  * Copyright 1998, 1999 Eric Kohl (ekohl@abo.rhein-zeitung.de)
5  * Copyright 1999 Alex Priem (alexp@sci.kun.nl)
6  * Copyright 1999 Chris Morgan <cmorgan@wpi.edu> and
7  *                James Abbatiello <abbeyj@wpi.edu>
8  * Copyright 2000 Uwe Bonnes <bon@elektron.ikp.physik.tu-darmstadt.de>
9  * Copyright 2009, 2010 Nikolay Sivov
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with this library; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24  *
25  * NOTE
26  * 
27  * This code was audited for completeness against the documented features
28  * of Comctl32.dll version 6.0 on Oct. 20, 2004, by Dimitrie O. Paun.
29  * 
30  * Unless otherwise noted, we believe this code to be complete, as per
31  * the specification mentioned above.
32  * If you discover missing features, or bugs, please note them below.
33  * 
34  * TODO:
35  *    -- MCM_[GS]ETUNICODEFORMAT
36  *    -- MONTHCAL_GetMonthRange
37  *    -- handle resources better (doesn't work now); 
38  *    -- take care of internationalization.
39  *    -- keyboard handling.
40  *    -- search for FIXME
41  */
42
43 #include <math.h>
44 #include <stdarg.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48
49 #include "windef.h"
50 #include "winbase.h"
51 #include "wingdi.h"
52 #include "winuser.h"
53 #include "winnls.h"
54 #include "commctrl.h"
55 #include "comctl32.h"
56 #include "uxtheme.h"
57 #include "tmschema.h"
58 #include "wine/unicode.h"
59 #include "wine/debug.h"
60
61 WINE_DEFAULT_DEBUG_CHANNEL(monthcal);
62
63 #define MC_SEL_LBUTUP       1   /* Left button released */
64 #define MC_SEL_LBUTDOWN     2   /* Left button pressed in calendar */
65 #define MC_PREVPRESSED      4   /* Prev month button pressed */
66 #define MC_NEXTPRESSED      8   /* Next month button pressed */
67 #define MC_PREVNEXTMONTHDELAY   350     /* when continuously pressing `next/prev
68                                            month', wait 350 ms before going
69                                            to the next/prev month */
70 #define MC_TODAYUPDATEDELAY 120000 /* time between today check for update (2 min) */
71
72 #define MC_PREVNEXTMONTHTIMER   1       /* Timer ID's */
73 #define MC_TODAYUPDATETIMER     2
74
75 #define countof(arr) (sizeof(arr)/sizeof(arr[0]))
76
77 /* convert from days to 100 nanoseconds unit - used as FILETIME unit */
78 #define DAYSTO100NSECS(days) (((ULONGLONG)(days))*24*60*60*10000000)
79
80 /* single calendar data */
81 typedef struct _CALENDAR_INFO
82 {
83     RECT title;      /* rect for the header above the calendar */
84     RECT titlemonth; /* the 'month name' text in the header */
85     RECT titleyear;  /* the 'year number' text in the header */
86     RECT wdays;      /* week days at top */
87     RECT days;       /* calendar area */
88     RECT weeknums;   /* week numbers at left side */
89
90     SYSTEMTIME month;/* contains calendar main month/year */
91 } CALENDAR_INFO;
92
93 typedef struct
94 {
95     HWND        hwndSelf;
96     DWORD       dwStyle; /* cached GWL_STYLE */
97
98     COLORREF    colors[MCSC_TRAILINGTEXT+1];
99
100     HFONT       hFont;
101     HFONT       hBoldFont;
102     int         textHeight;
103     int         textWidth;
104     int         height_increment;
105     int         width_increment;
106     INT         delta;  /* scroll rate; # of months that the */
107                         /* control moves when user clicks a scroll button */
108     int         visible;        /* # of months visible */
109     int         firstDay;       /* Start month calendar with firstDay's day,
110                                    stored in SYSTEMTIME format */
111     BOOL        firstDaySet;    /* first week day differs from locale defined */
112
113     BOOL        isUnicode;      /* value set with MCM_SETUNICODE format */
114
115     int         monthRange;
116     MONTHDAYSTATE *monthdayState;
117     SYSTEMTIME  todaysDate;
118     BOOL        todaySet;       /* Today was forced with MCM_SETTODAY */
119     int         status;         /* See MC_SEL flags */
120     SYSTEMTIME  firstSel;       /* first selected day */
121     INT         maxSelCount;
122     SYSTEMTIME  minSel;         /* contains single selection when used without MCS_MULTISELECT */
123     SYSTEMTIME  maxSel;
124     SYSTEMTIME  focusedSel;     /* date currently focused with mouse movement */
125     DWORD       rangeValid;
126     SYSTEMTIME  minDate;
127     SYSTEMTIME  maxDate;
128
129     RECT titlebtnnext;  /* the `next month' button in the header */
130     RECT titlebtnprev;  /* the `prev month' button in the header */
131     RECT todayrect;     /* `today: xx/xx/xx' text rect */
132     HWND hwndNotify;    /* Window to receive the notifications */
133     HWND hWndYearEdit;  /* Window Handle of edit box to handle years */
134     HWND hWndYearUpDown;/* Window Handle of updown box to handle years */
135     WNDPROC EditWndProc;  /* original Edit window procedure */
136
137     CALENDAR_INFO *calendars;
138     INT            cal_num;
139 } MONTHCAL_INFO, *LPMONTHCAL_INFO;
140
141 static const WCHAR themeClass[] = { 'S','c','r','o','l','l','b','a','r',0 };
142
143 /* empty SYSTEMTIME const */
144 static const SYSTEMTIME st_null;
145 /* valid date limits */
146 static const SYSTEMTIME max_allowed_date = { .wYear = 9999, .wMonth = 12, .wDay = 31 };
147 static const SYSTEMTIME min_allowed_date = { .wYear = 1752, .wMonth = 9,  .wDay = 14 };
148
149 /* Prev/Next buttons */
150 enum nav_direction
151 {
152     DIRECTION_BACKWARD,
153     DIRECTION_FORWARD
154 };
155
156 /* helper functions  */
157
158 /* send a single MCN_SELCHANGE notification */
159 static inline void MONTHCAL_NotifySelectionChange(const MONTHCAL_INFO *infoPtr)
160 {
161     NMSELCHANGE nmsc;
162
163     nmsc.nmhdr.hwndFrom = infoPtr->hwndSelf;
164     nmsc.nmhdr.idFrom   = GetWindowLongPtrW(infoPtr->hwndSelf, GWLP_ID);
165     nmsc.nmhdr.code     = MCN_SELCHANGE;
166     nmsc.stSelStart     = infoPtr->minSel;
167     nmsc.stSelEnd       = infoPtr->maxSel;
168     SendMessageW(infoPtr->hwndNotify, WM_NOTIFY, nmsc.nmhdr.idFrom, (LPARAM)&nmsc);
169 }
170
171 /* send a single MCN_SELECT notification */
172 static inline void MONTHCAL_NotifySelect(const MONTHCAL_INFO *infoPtr)
173 {
174     NMSELCHANGE nmsc;
175
176     nmsc.nmhdr.hwndFrom = infoPtr->hwndSelf;
177     nmsc.nmhdr.idFrom   = GetWindowLongPtrW(infoPtr->hwndSelf, GWLP_ID);
178     nmsc.nmhdr.code     = MCN_SELECT;
179     nmsc.stSelStart     = infoPtr->minSel;
180     nmsc.stSelEnd       = infoPtr->maxSel;
181
182     SendMessageW(infoPtr->hwndNotify, WM_NOTIFY, nmsc.nmhdr.idFrom, (LPARAM)&nmsc);
183 }
184
185 /* returns the number of days in any given month, checking for leap days */
186 /* january is 1, december is 12 */
187 int MONTHCAL_MonthLength(int month, int year)
188 {
189   const int mdays[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
190   /* Wrap around, this eases handling. Getting length only we shouldn't care
191      about year change here cause January and December have
192      the same day quantity */
193   if(month == 0)
194     month = 12;
195   else if(month == 13)
196     month = 1;
197
198   /* special case for calendar transition year */
199   if(month == min_allowed_date.wMonth && year == min_allowed_date.wYear) return 19;
200
201   /* if we have a leap year add 1 day to February */
202   /* a leap year is a year either divisible by 400 */
203   /* or divisible by 4 and not by 100 */
204   if(month == 2) { /* February */
205     return mdays[month - 1] + ((year%400 == 0) ? 1 : ((year%100 != 0) &&
206      (year%4 == 0)) ? 1 : 0);
207   }
208   else {
209     return mdays[month - 1];
210   }
211 }
212
213 /* compares timestamps using date part only */
214 static inline BOOL MONTHCAL_IsDateEqual(const SYSTEMTIME *first, const SYSTEMTIME *second)
215 {
216   return (first->wYear == second->wYear) && (first->wMonth == second->wMonth) &&
217          (first->wDay  == second->wDay);
218 }
219
220 /* make sure that date fields are valid */
221 static BOOL MONTHCAL_ValidateDate(const SYSTEMTIME *time)
222 {
223   if(time->wMonth < 1 || time->wMonth > 12 ) return FALSE;
224   if(time->wDayOfWeek > 6) return FALSE;
225   if(time->wDay > MONTHCAL_MonthLength(time->wMonth, time->wYear))
226           return FALSE;
227
228   return TRUE;
229 }
230
231 /* Copies timestamp part only.
232  *
233  * PARAMETERS
234  *
235  *  [I] from : source date
236  *  [O] to   : dest date
237  */
238 static void MONTHCAL_CopyTime(const SYSTEMTIME *from, SYSTEMTIME *to)
239 {
240   to->wHour   = from->wHour;
241   to->wMinute = from->wMinute;
242   to->wSecond = from->wSecond;
243 }
244
245 /* Copies date part only.
246  *
247  * PARAMETERS
248  *
249  *  [I] from : source date
250  *  [O] to   : dest date
251  */
252 static void MONTHCAL_CopyDate(const SYSTEMTIME *from, SYSTEMTIME *to)
253 {
254   to->wYear  = from->wYear;
255   to->wMonth = from->wMonth;
256   to->wDay   = from->wDay;
257   to->wDayOfWeek = from->wDayOfWeek;
258 }
259
260 /* Compares two dates in SYSTEMTIME format
261  *
262  * PARAMETERS
263  *
264  *  [I] first  : pointer to valid first date data to compare
265  *  [I] second : pointer to valid second date data to compare
266  *
267  * RETURN VALUE
268  *
269  *  -1 : first <  second
270  *   0 : first == second
271  *   1 : first >  second
272  *
273  *  Note that no date validation performed, alreadt validated values expected.
274  */
275 static LONG MONTHCAL_CompareSystemTime(const SYSTEMTIME *first, const SYSTEMTIME *second)
276 {
277   FILETIME ft_first, ft_second;
278
279   SystemTimeToFileTime(first, &ft_first);
280   SystemTimeToFileTime(second, &ft_second);
281
282   return CompareFileTime(&ft_first, &ft_second);
283 }
284
285 static LONG MONTHCAL_CompareMonths(const SYSTEMTIME *first, const SYSTEMTIME *second)
286 {
287   SYSTEMTIME st_first, st_second;
288
289   st_first = st_second = st_null;
290   MONTHCAL_CopyDate(first, &st_first);
291   MONTHCAL_CopyDate(second, &st_second);
292   st_first.wDay = st_second.wDay = 1;
293
294   return MONTHCAL_CompareSystemTime(&st_first, &st_second);
295 }
296
297 static LONG MONTHCAL_CompareDate(const SYSTEMTIME *first, const SYSTEMTIME *second)
298 {
299   SYSTEMTIME st_first, st_second;
300
301   st_first = st_second = st_null;
302   MONTHCAL_CopyDate(first, &st_first);
303   MONTHCAL_CopyDate(second, &st_second);
304
305   return MONTHCAL_CompareSystemTime(&st_first, &st_second);
306 }
307
308 /* Checks largest possible date range and configured one
309  *
310  * PARAMETERS
311  *
312  *  [I] infoPtr : valid pointer to control data
313  *  [I] date    : pointer to valid date data to check
314  *  [I] fix     : make date fit valid range
315  *
316  * RETURN VALUE
317  *
318  *  TRUE  - date whithin largest and configured range
319  *  FALSE - date is outside largest or configured range
320  */
321 static BOOL MONTHCAL_IsDateInValidRange(const MONTHCAL_INFO *infoPtr,
322                                         SYSTEMTIME *date, BOOL fix)
323 {
324   const SYSTEMTIME *fix_st = NULL;
325
326   if(MONTHCAL_CompareSystemTime(date, &max_allowed_date) == 1) {
327      fix_st = &max_allowed_date;
328   }
329   else if(MONTHCAL_CompareSystemTime(date, &min_allowed_date) == -1) {
330      fix_st = &min_allowed_date;
331   }
332   else if(infoPtr->rangeValid & GDTR_MAX) {
333      if((MONTHCAL_CompareSystemTime(date, &infoPtr->maxDate) == 1)) {
334        fix_st = &infoPtr->maxDate;
335      }
336   }
337   else if(infoPtr->rangeValid & GDTR_MIN) {
338      if((MONTHCAL_CompareSystemTime(date, &infoPtr->minDate) == -1)) {
339        fix_st = &infoPtr->minDate;
340      }
341   }
342
343   if (fix && fix_st) {
344     date->wYear  = fix_st->wYear;
345     date->wMonth = fix_st->wMonth;
346   }
347
348   return fix_st ? FALSE : TRUE;
349 }
350
351 /* Checks passed range width with configured maximum selection count
352  *
353  * PARAMETERS
354  *
355  *  [I] infoPtr : valid pointer to control data
356  *  [I] range0  : pointer to valid date data (requested bound)
357  *  [I] range1  : pointer to valid date data (primary bound)
358  *  [O] adjust  : returns adjusted range bound to fit maximum range (optional)
359  *
360  *  Adjust value computed basing on primary bound and current maximum selection
361  *  count. For simple range check (without adjusted value required) (range0, range1)
362  *  relation means nothing.
363  *
364  * RETURN VALUE
365  *
366  *  TRUE  - range is shorter or equal to maximum
367  *  FALSE - range is larger than maximum
368  */
369 static BOOL MONTHCAL_IsSelRangeValid(const MONTHCAL_INFO *infoPtr,
370                                      const SYSTEMTIME *range0,
371                                      const SYSTEMTIME *range1,
372                                      SYSTEMTIME *adjust)
373 {
374   ULARGE_INTEGER ul_range0, ul_range1, ul_diff;
375   FILETIME ft_range0, ft_range1;
376   LONG cmp;
377
378   SystemTimeToFileTime(range0, &ft_range0);
379   SystemTimeToFileTime(range1, &ft_range1);
380
381   ul_range0.u.LowPart  = ft_range0.dwLowDateTime;
382   ul_range0.u.HighPart = ft_range0.dwHighDateTime;
383   ul_range1.u.LowPart  = ft_range1.dwLowDateTime;
384   ul_range1.u.HighPart = ft_range1.dwHighDateTime;
385
386   cmp = CompareFileTime(&ft_range0, &ft_range1);
387
388   if(cmp == 1)
389      ul_diff.QuadPart = ul_range0.QuadPart - ul_range1.QuadPart;
390   else
391      ul_diff.QuadPart = -ul_range0.QuadPart + ul_range1.QuadPart;
392
393   if(ul_diff.QuadPart >= DAYSTO100NSECS(infoPtr->maxSelCount)) {
394
395      if(adjust) {
396        if(cmp == 1)
397           ul_range0.QuadPart = ul_range1.QuadPart + DAYSTO100NSECS(infoPtr->maxSelCount - 1);
398        else
399           ul_range0.QuadPart = ul_range1.QuadPart - DAYSTO100NSECS(infoPtr->maxSelCount - 1);
400
401        ft_range0.dwLowDateTime  = ul_range0.u.LowPart;
402        ft_range0.dwHighDateTime = ul_range0.u.HighPart;
403        FileTimeToSystemTime(&ft_range0, adjust);
404      }
405
406      return FALSE;
407   }
408   else return TRUE;
409 }
410
411 /* Used in MCM_SETRANGE/MCM_SETSELRANGE to determine resulting time part.
412    Milliseconds are intentionally not validated. */
413 static BOOL MONTHCAL_ValidateTime(const SYSTEMTIME *time)
414 {
415   if((time->wHour > 24) || (time->wMinute > 59) || (time->wSecond > 59))
416     return FALSE;
417   else
418     return TRUE;
419 }
420
421 /* Note:Depending on DST, this may be offset by a day.
422    Need to find out if we're on a DST place & adjust the clock accordingly.
423    Above function assumes we have a valid data.
424    Valid for year>1752;  1 <= d <= 31, 1 <= m <= 12.
425    0 = Sunday.
426 */
427
428 /* Returns the day in the week
429  *
430  * PARAMETERS
431  *  [i] date    : input date
432  *  [I] inplace : set calculated value back to date structure
433  *
434  * RETURN VALUE
435  *   day of week in SYSTEMTIME format: (0 == sunday,..., 6 == saturday)
436  */
437 int MONTHCAL_CalculateDayOfWeek(SYSTEMTIME *date, BOOL inplace)
438 {
439   SYSTEMTIME st = st_null;
440   FILETIME ft;
441
442   MONTHCAL_CopyDate(date, &st);
443
444   SystemTimeToFileTime(&st, &ft);
445   FileTimeToSystemTime(&ft, &st);
446
447   if (inplace) date->wDayOfWeek = st.wDayOfWeek;
448
449   return st.wDayOfWeek;
450 }
451
452 /* add/substract 'months' from date */
453 static inline void MONTHCAL_GetMonth(SYSTEMTIME *date, INT months)
454 {
455   INT length, m = date->wMonth + months;
456
457   date->wYear += m > 0 ? (m - 1) / 12 : m / 12 - 1;
458   date->wMonth = m > 0 ? (m - 1) % 12 + 1 : 12 + m % 12;
459   /* fix moving from last day in a month */
460   length = MONTHCAL_MonthLength(date->wMonth, date->wYear);
461   if(date->wDay > length) date->wDay = length;
462   MONTHCAL_CalculateDayOfWeek(date, TRUE);
463 }
464
465 /* properly updates date to point on next month */
466 static inline void MONTHCAL_GetNextMonth(SYSTEMTIME *date)
467 {
468   return MONTHCAL_GetMonth(date, 1);
469 }
470
471 /* properly updates date to point on prev month */
472 static inline void MONTHCAL_GetPrevMonth(SYSTEMTIME *date)
473 {
474   return MONTHCAL_GetMonth(date, -1);
475 }
476
477 /* Returns full date for a first currently visible day */
478 static void MONTHCAL_GetMinDate(const MONTHCAL_INFO *infoPtr, SYSTEMTIME *date)
479 {
480   /* zero indexed calendar has the earliest date */
481   SYSTEMTIME st_first = infoPtr->calendars[0].month;
482   INT firstDay;
483
484   st_first.wDay = 1;
485   firstDay = MONTHCAL_CalculateDayOfWeek(&st_first, FALSE);
486
487   *date = infoPtr->calendars[0].month;
488   MONTHCAL_GetPrevMonth(date);
489
490   date->wDay = MONTHCAL_MonthLength(date->wMonth, date->wYear) +
491                (infoPtr->firstDay - firstDay) % 7 + 1;
492
493   if(date->wDay > MONTHCAL_MonthLength(date->wMonth, date->wYear))
494     date->wDay -= 7;
495
496   /* fix day of week */
497   MONTHCAL_CalculateDayOfWeek(date, TRUE);
498 }
499
500 /* Returns full date for a last currently visible day */
501 static void MONTHCAL_GetMaxDate(const MONTHCAL_INFO *infoPtr, SYSTEMTIME *date)
502 {
503   /* the latest date is in latest calendar */
504   SYSTEMTIME st, lt_month = infoPtr->calendars[infoPtr->cal_num-1].month;
505
506   *date = lt_month;
507   MONTHCAL_GetNextMonth(date);
508
509   MONTHCAL_GetMinDate(infoPtr, &st);
510   /* Use month length to get max day. 42 means max day count in calendar area */
511   date->wDay = 42 - (MONTHCAL_MonthLength(st.wMonth, st.wYear) - st.wDay + 1) -
512                      MONTHCAL_MonthLength(lt_month.wMonth, lt_month.wYear);
513
514   /* fix day of week */
515   MONTHCAL_CalculateDayOfWeek(date, TRUE);
516 }
517
518 /* From a given point, calculate the row (weekpos), column(daypos)
519    and day in the calendar. day== 0 mean the last day of tha last month
520 */
521 static int MONTHCAL_CalcDayFromPos(const MONTHCAL_INFO *infoPtr, int x, int y,
522                                    int *daypos, int *weekpos)
523 {
524   int retval, firstDay;
525   RECT rcClient;
526   SYSTEMTIME st = infoPtr->minSel;
527
528   GetClientRect(infoPtr->hwndSelf, &rcClient);
529
530   /* if the point is outside the x bounds of the window put
531   it at the boundary */
532   if (x > rcClient.right)
533     x = rcClient.right;
534
535   *daypos  = (x - infoPtr->calendars[0].days.left ) / infoPtr->width_increment;
536   *weekpos = (y - infoPtr->calendars[0].days.top ) / infoPtr->height_increment;
537
538   st.wDay = 1;
539   firstDay = (MONTHCAL_CalculateDayOfWeek(&st, FALSE) + 6 - infoPtr->firstDay) % 7;
540   retval = *daypos + (7 * *weekpos) - firstDay;
541   return retval;
542 }
543
544 /* Sets the RECT struct r to the rectangle around the date
545  *
546  * PARAMETERS
547  *
548  *  [I] infoPtr : pointer to control data
549  *  [I] date : date value
550  *  [O] x : day column (zero based)
551  *  [O] y : week column (zero based)
552  */
553 static void MONTHCAL_CalcDayXY(const MONTHCAL_INFO *infoPtr,
554                                const SYSTEMTIME *date, INT *x, INT *y)
555 {
556   SYSTEMTIME st = infoPtr->minSel;
557   LONG cmp;
558   int first;
559
560   st.wDay = 1;
561   first = (MONTHCAL_CalculateDayOfWeek(&st, FALSE) + 6 - infoPtr->firstDay) % 7;
562
563   cmp = MONTHCAL_CompareMonths(date, &infoPtr->minSel);
564
565   /* previous month */
566   if(cmp == -1) {
567     *x = (first - MONTHCAL_MonthLength(date->wMonth, infoPtr->minSel.wYear) + date->wDay) % 7;
568     *y = 0;
569     return;
570   }
571
572   /* next month calculation is same as for current,
573      just add current month length */
574   if(cmp == 1) {
575     first += MONTHCAL_MonthLength(infoPtr->minSel.wMonth, infoPtr->minSel.wYear);
576   }
577
578   *x = (date->wDay + first) % 7;
579   *y = (date->wDay + first - *x) / 7;
580 }
581
582
583 /* x: column(day), y: row(week) */
584 static inline void MONTHCAL_CalcDayRect(const MONTHCAL_INFO *infoPtr, RECT *r, int x, int y)
585 {
586   r->left = infoPtr->calendars[0].days.left + x * infoPtr->width_increment;
587   r->right = r->left + infoPtr->width_increment;
588   r->top  = infoPtr->calendars[0].days.top  + y * infoPtr->height_increment;
589   r->bottom = r->top + infoPtr->textHeight;
590 }
591
592
593 /* Sets the RECT struct r to the rectangle around the date */
594 static inline void MONTHCAL_CalcPosFromDay(const MONTHCAL_INFO *infoPtr,
595                                            const SYSTEMTIME *date, RECT *r)
596 {
597   int x, y;
598
599   MONTHCAL_CalcDayXY(infoPtr, date, &x, &y);
600   MONTHCAL_CalcDayRect(infoPtr, r, x, y);
601 }
602
603 /* Focused day helper:
604
605    - set focused date to given value;
606    - reset to zero value if NULL passed;
607    - invalidate previous and new day rectangle only if needed.
608
609    Returns TRUE if focused day changed, FALSE otherwise.
610 */
611 static BOOL MONTHCAL_SetDayFocus(MONTHCAL_INFO *infoPtr, const SYSTEMTIME *st)
612 {
613   RECT r;
614
615   if(st)
616   {
617     /* there's nothing to do if it's the same date,
618        mouse move within same date rectangle case */
619     if(MONTHCAL_IsDateEqual(&infoPtr->focusedSel, st)) return FALSE;
620
621     /* invalidate old focused day */
622     MONTHCAL_CalcPosFromDay(infoPtr, &infoPtr->focusedSel, &r);
623     InvalidateRect(infoPtr->hwndSelf, &r, FALSE);
624
625     infoPtr->focusedSel = *st;
626   }
627
628   MONTHCAL_CalcPosFromDay(infoPtr, &infoPtr->focusedSel, &r);
629
630   if(!st && MONTHCAL_ValidateDate(&infoPtr->focusedSel))
631     infoPtr->focusedSel = st_null;
632
633   /* on set invalidates new day, on reset clears previous focused day */
634   InvalidateRect(infoPtr->hwndSelf, &r, FALSE);
635
636   return TRUE;
637 }
638
639 /* Draw today day mark rectangle
640  *
641  * [I] hdc : context to draw in
642  * [I] day : day to mark with rectangle
643  *
644  */
645 static void MONTHCAL_CircleDay(const MONTHCAL_INFO *infoPtr, HDC hdc,
646                                const SYSTEMTIME *date)
647 {
648   HPEN hRedPen = CreatePen(PS_SOLID, 1, RGB(255, 0, 0));
649   HPEN hOldPen2 = SelectObject(hdc, hRedPen);
650   HBRUSH hOldBrush;
651   RECT day_rect;
652
653   MONTHCAL_CalcPosFromDay(infoPtr, date, &day_rect);
654
655   hOldBrush = SelectObject(hdc, GetStockObject(NULL_BRUSH));
656   Rectangle(hdc, day_rect.left, day_rect.top, day_rect.right, day_rect.bottom);
657
658   SelectObject(hdc, hOldBrush);
659   DeleteObject(hRedPen);
660   SelectObject(hdc, hOldPen2);
661 }
662
663 static void MONTHCAL_DrawDay(const MONTHCAL_INFO *infoPtr, HDC hdc, const SYSTEMTIME *st,
664                              int bold, const PAINTSTRUCT *ps)
665 {
666   static const WCHAR fmtW[] = { '%','d',0 };
667   WCHAR buf[10];
668   RECT r, r_temp;
669   static BOOL bold_selected;
670   BOOL selected_day = FALSE;
671   HBRUSH hbr;
672   COLORREF oldCol = 0;
673   COLORREF oldBk  = 0;
674
675 /* No need to check styles: when selection is not valid, it is set to zero.
676  * 1<day<31, so everything is OK.
677  */
678
679   MONTHCAL_CalcPosFromDay(infoPtr, st, &r);
680   if(!IntersectRect(&r_temp, &(ps->rcPaint), &r)) return;
681
682   if ((MONTHCAL_CompareDate(st, &infoPtr->minSel) >= 0) &&
683       (MONTHCAL_CompareDate(st, &infoPtr->maxSel) <= 0)) {
684
685     TRACE("%d %d %d\n", st->wDay, infoPtr->minSel.wDay, infoPtr->maxSel.wDay);
686     TRACE("%s\n", wine_dbgstr_rect(&r));
687     oldCol = SetTextColor(hdc, infoPtr->colors[MCSC_MONTHBK]);
688     oldBk = SetBkColor(hdc, infoPtr->colors[MCSC_TRAILINGTEXT]);
689     hbr = GetSysColorBrush(COLOR_HIGHLIGHT);
690     FillRect(hdc, &r, hbr);
691
692     selected_day = TRUE;
693   }
694
695   if(bold && !bold_selected) {
696     SelectObject(hdc, infoPtr->hBoldFont);
697     bold_selected = TRUE;
698   }
699   if(!bold && bold_selected) {
700     SelectObject(hdc, infoPtr->hFont);
701     bold_selected = FALSE;
702   }
703
704   SetBkMode(hdc,TRANSPARENT);
705   wsprintfW(buf, fmtW, st->wDay);
706   DrawTextW(hdc, buf, -1, &r, DT_CENTER | DT_VCENTER | DT_SINGLELINE );
707
708   if(selected_day) {
709     SetTextColor(hdc, oldCol);
710     SetBkColor(hdc, oldBk);
711   }
712 }
713
714
715 static void MONTHCAL_PaintButton(MONTHCAL_INFO *infoPtr, HDC hdc, enum nav_direction button)
716 {
717     HTHEME theme = GetWindowTheme (infoPtr->hwndSelf);
718     RECT *r = button == DIRECTION_FORWARD ? &infoPtr->titlebtnnext : &infoPtr->titlebtnprev;
719     BOOL pressed = button == DIRECTION_FORWARD ? infoPtr->status & MC_NEXTPRESSED :
720                                                  infoPtr->status & MC_PREVPRESSED;
721     if (theme)
722     {
723         static const int states[] = {
724             /* Prev button */
725             ABS_LEFTNORMAL,  ABS_LEFTPRESSED,  ABS_LEFTDISABLED,
726             /* Next button */
727             ABS_RIGHTNORMAL, ABS_RIGHTPRESSED, ABS_RIGHTDISABLED
728         };
729         int stateNum = button == DIRECTION_FORWARD ? 3 : 0;
730         if (pressed)
731             stateNum += 1;
732         else
733         {
734             if (infoPtr->dwStyle & WS_DISABLED) stateNum += 2;
735         }
736         DrawThemeBackground (theme, hdc, SBP_ARROWBTN, states[stateNum], r, NULL);
737     }
738     else
739     {
740         int style = button == DIRECTION_FORWARD ? DFCS_SCROLLRIGHT : DFCS_SCROLLLEFT;
741         if (pressed)
742             style |= DFCS_PUSHED;
743         else
744         {
745             if (infoPtr->dwStyle & WS_DISABLED) style |= DFCS_INACTIVE;
746         }
747         
748         DrawFrameControl(hdc, r, DFC_SCROLL, style);
749     }
750 }
751 /* paint a title with buttons and month/year string */
752 static void MONTHCAL_PaintTitle(MONTHCAL_INFO *infoPtr, HDC hdc, const PAINTSTRUCT *ps, INT calIdx)
753 {
754   static const WCHAR fmt_monthW[] = { '%','s',' ','%','l','d',0 };
755   RECT *title = &infoPtr->calendars[calIdx].title;
756   const SYSTEMTIME *st = &infoPtr->calendars[calIdx].month;
757   WCHAR buf_month[80], buf_fmt[80];
758   HBRUSH hbr;
759   SIZE sz;
760
761   /* fill header box */
762   hbr = CreateSolidBrush(infoPtr->colors[MCSC_TITLEBK]);
763   FillRect(hdc, title, hbr);
764   DeleteObject(hbr);
765
766   /* month/year string */
767   SetBkColor(hdc, infoPtr->colors[MCSC_TITLEBK]);
768   SetTextColor(hdc, infoPtr->colors[MCSC_TITLETEXT]);
769   SelectObject(hdc, infoPtr->hBoldFont);
770
771   GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SMONTHNAME1 + st->wMonth - 1,
772                  buf_month, countof(buf_month));
773
774   wsprintfW(buf_fmt, fmt_monthW, buf_month, st->wYear);
775   DrawTextW(hdc, buf_fmt, strlenW(buf_fmt), title,
776                       DT_CENTER | DT_VCENTER | DT_SINGLELINE);
777
778   /* update title rectangles with current month - used while testing hits */
779   GetTextExtentPoint32W(hdc, buf_fmt, strlenW(buf_fmt), &sz);
780   infoPtr->calendars[calIdx].titlemonth.left = title->right / 2 + title->left / 2 - sz.cx / 2;
781   infoPtr->calendars[calIdx].titleyear.right = title->right / 2 + title->left / 2 + sz.cx / 2;
782
783   GetTextExtentPoint32W(hdc, buf_month, strlenW(buf_month), &sz);
784   infoPtr->calendars[calIdx].titlemonth.right = infoPtr->calendars[calIdx].titlemonth.left + sz.cx;
785   infoPtr->calendars[calIdx].titleyear.left   = infoPtr->calendars[calIdx].titlemonth.right;
786 }
787
788 static void MONTHCAL_PaintWeeknumbers(const MONTHCAL_INFO *infoPtr, HDC hdc, const PAINTSTRUCT *ps, INT calIdx)
789 {
790   const SYSTEMTIME *date = &infoPtr->calendars[calIdx].month;
791   static const WCHAR fmt_weekW[] = { '%','d',0 };
792   INT mindays, weeknum, weeknum1, startofprescal;
793   INT i, prev_month;
794   SYSTEMTIME st;
795   WCHAR buf[80];
796   HBRUSH hbr;
797   RECT r;
798
799   if (!(infoPtr->dwStyle & MCS_WEEKNUMBERS)) return;
800
801   MONTHCAL_GetMinDate(infoPtr, &st);
802   startofprescal = st.wDay;
803   st = *date;
804
805   prev_month = date->wMonth - 1;
806   if(prev_month == 0) prev_month = 12;
807
808   /*
809      Rules what week to call the first week of a new year:
810      LOCALE_IFIRSTWEEKOFYEAR == 0 (e.g US?):
811      The week containing Jan 1 is the first week of year
812      LOCALE_IFIRSTWEEKOFYEAR == 2 (e.g. Germany):
813      First week of year must contain 4 days of the new year
814      LOCALE_IFIRSTWEEKOFYEAR == 1  (what contries?)
815      The first week of the year must contain only days of the new year
816   */
817   GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_IFIRSTWEEKOFYEAR, buf, countof(buf));
818   weeknum = atoiW(buf);
819   switch (weeknum)
820   {
821     case 1: mindays = 6;
822         break;
823     case 2: mindays = 3;
824         break;
825     case 0: mindays = 0;
826         break;
827     default:
828         WARN("Unknown LOCALE_IFIRSTWEEKOFYEAR value %d, defaulting to 0\n", weeknum);
829         mindays = 0;
830   }
831
832   if (date->wMonth == 1)
833   {
834     /* calculate all those exceptions for january */
835     st.wDay = st.wMonth = 1;
836     weeknum1 = MONTHCAL_CalculateDayOfWeek(&st, FALSE);
837     if ((infoPtr->firstDay - weeknum1) % 7 > mindays)
838         weeknum = 1;
839     else
840     {
841         weeknum = 0;
842         for(i = 0; i < 11; i++)
843            weeknum += MONTHCAL_MonthLength(i+1, date->wYear - 1);
844
845         weeknum  += startofprescal + 7;
846         weeknum  /= 7;
847         st.wYear -= 1;
848         weeknum1  = MONTHCAL_CalculateDayOfWeek(&st, FALSE);
849         if ((infoPtr->firstDay - weeknum1) % 7 > mindays) weeknum++;
850     }
851   }
852   else
853   {
854     weeknum = 0;
855     for(i = 0; i < prev_month - 1; i++)
856         weeknum += MONTHCAL_MonthLength(i+1, date->wYear);
857
858     weeknum += startofprescal + 7;
859     weeknum /= 7;
860     st.wDay = st.wMonth = 1;
861     weeknum1 = MONTHCAL_CalculateDayOfWeek(&st, FALSE);
862     if ((infoPtr->firstDay - weeknum1) % 7 > mindays) weeknum++;
863   }
864
865   r = infoPtr->calendars[calIdx].weeknums;
866
867   /* erase whole week numbers area */
868   hbr = CreateSolidBrush(infoPtr->colors[MCSC_MONTHBK]);
869   FillRect(hdc, &r, hbr);
870   DeleteObject(hbr);
871
872   /* reduce rectangle to one week number */
873   r.bottom = r.top + infoPtr->height_increment;
874
875   for(i = 0; i < 6; i++) {
876     if((i == 0) && (weeknum > 50))
877     {
878         wsprintfW(buf, fmt_weekW, weeknum);
879         weeknum = 0;
880     }
881     else if((i == 5) && (weeknum > 47))
882     {
883         wsprintfW(buf, fmt_weekW, 1);
884     }
885     else
886         wsprintfW(buf, fmt_weekW, weeknum + i);
887
888     DrawTextW(hdc, buf, -1, &r, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
889     OffsetRect(&r, 0, infoPtr->height_increment);
890   }
891
892   /* line separator for week numbers column */
893   MoveToEx(hdc, infoPtr->calendars[calIdx].weeknums.right, infoPtr->calendars[calIdx].weeknums.top + 3 , NULL);
894   LineTo(hdc,   infoPtr->calendars[calIdx].weeknums.right, infoPtr->calendars[calIdx].weeknums.bottom);
895 }
896
897 /* bottom today date */
898 static void MONTHCAL_PaintTodayTitle(const MONTHCAL_INFO *infoPtr, HDC hdc, const PAINTSTRUCT *ps)
899 {
900   if(!(infoPtr->dwStyle & MCS_NOTODAY))  {
901     static const WCHAR todayW[] = { 'T','o','d','a','y',':',0 };
902     static const WCHAR fmt_todayW[] = { '%','s',' ','%','s',0 };
903     WCHAR buf_todayW[30], buf_dateW[20], buf[80];
904     RECT rtoday;
905
906     if(!(infoPtr->dwStyle & MCS_NOTODAYCIRCLE)) {
907       SYSTEMTIME fake_st;
908
909       MONTHCAL_GetMaxDate(infoPtr, &fake_st);
910       /* this is always safe cause next month will never fully fit calendar */
911       fake_st.wDay += 1;
912       MONTHCAL_CircleDay(infoPtr, hdc, &fake_st);
913     }
914     if (!LoadStringW(COMCTL32_hModule, IDM_TODAY, buf_todayW, countof(buf_todayW)))
915     {
916         WARN("Can't load resource\n");
917         strcpyW(buf_todayW, todayW);
918     }
919     MONTHCAL_CalcDayRect(infoPtr, &rtoday, 1, 6);
920     GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &infoPtr->todaysDate, NULL,
921                                                         buf_dateW, countof(buf_dateW));
922     SelectObject(hdc, infoPtr->hBoldFont);
923
924     wsprintfW(buf, fmt_todayW, buf_todayW, buf_dateW);
925     DrawTextW(hdc, buf, -1, &rtoday, DT_CALCRECT | DT_LEFT | DT_VCENTER | DT_SINGLELINE);
926     DrawTextW(hdc, buf, -1, &rtoday, DT_LEFT | DT_VCENTER | DT_SINGLELINE);
927
928     SelectObject(hdc, infoPtr->hFont);
929   }
930 }
931
932 /* today mark + focus */
933 static void MONTHCAL_PaintFocusAndCircle(const MONTHCAL_INFO *infoPtr, HDC hdc, const PAINTSTRUCT *ps)
934 {
935   if((infoPtr->minSel.wMonth == infoPtr->todaysDate.wMonth) &&
936      (infoPtr->minSel.wYear  == infoPtr->todaysDate.wYear) &&
937     !(infoPtr->dwStyle & MCS_NOTODAYCIRCLE))
938   {
939     MONTHCAL_CircleDay(infoPtr, hdc, &infoPtr->todaysDate);
940   }
941
942   if(!MONTHCAL_IsDateEqual(&infoPtr->focusedSel, &st_null))
943   {
944     RECT r;
945     MONTHCAL_CalcPosFromDay(infoPtr, &infoPtr->focusedSel, &r);
946     DrawFocusRect(hdc, &r);
947   }
948 }
949
950 /* paint a calendar area */
951 static void MONTHCAL_PaintCalendar(const MONTHCAL_INFO *infoPtr, HDC hdc, const PAINTSTRUCT *ps, INT calIdx)
952 {
953   const SYSTEMTIME *date = &infoPtr->calendars[calIdx].month;
954   INT prev_month, i, j, length;
955   RECT r, fill_bk_rect;
956   SYSTEMTIME st;
957   WCHAR buf[80];
958   HBRUSH hbr;
959   int mask;
960
961   /* fill whole days area - from week days area to today note rectangle */
962   fill_bk_rect = infoPtr->calendars[calIdx].wdays;
963   fill_bk_rect.bottom = infoPtr->calendars[calIdx].days.bottom +
964                           (infoPtr->todayrect.bottom - infoPtr->todayrect.top);
965
966   hbr = CreateSolidBrush(infoPtr->colors[MCSC_MONTHBK]);
967   FillRect(hdc, &fill_bk_rect, hbr);
968   DeleteObject(hbr);
969
970   /* draw line under day abbreviations */
971   MoveToEx(hdc, infoPtr->calendars[calIdx].days.left + 3,
972                 infoPtr->calendars[calIdx].title.bottom + infoPtr->textHeight + 1, NULL);
973   LineTo(hdc, infoPtr->calendars[calIdx].days.right - 3,
974               infoPtr->calendars[calIdx].title.bottom + infoPtr->textHeight + 1);
975
976   prev_month = date->wMonth - 1;
977   if (prev_month == 0) prev_month = 12;
978
979   infoPtr->calendars[calIdx].wdays.left = infoPtr->calendars[calIdx].days.left =
980       infoPtr->calendars[calIdx].weeknums.right;
981
982   /* 1. draw day abbreviations */
983   SelectObject(hdc, infoPtr->hFont);
984   SetBkColor(hdc, infoPtr->colors[MCSC_MONTHBK]);
985   SetTextColor(hdc, infoPtr->colors[MCSC_TRAILINGTEXT]);
986   /* rectangle to draw a single day abbreviation within */
987   r = infoPtr->calendars[calIdx].wdays;
988   r.right = r.left + infoPtr->width_increment;
989
990   i = infoPtr->firstDay;
991   for(j = 0; j < 7; j++) {
992     GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SABBREVDAYNAME1 + (i+j+6)%7, buf, countof(buf));
993     DrawTextW(hdc, buf, strlenW(buf), &r, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
994     OffsetRect(&r, infoPtr->width_increment, 0);
995   }
996
997   /* 2. previous and next months */
998   if (!(infoPtr->dwStyle & MCS_NOTRAILINGDATES) && (calIdx == 0 || calIdx == infoPtr->cal_num - 1))
999   {
1000     SYSTEMTIME st_max;
1001
1002     SetTextColor(hdc, infoPtr->colors[MCSC_TRAILINGTEXT]);
1003
1004     /* draw prev month */
1005     if (calIdx == 0)
1006     {
1007       MONTHCAL_GetMinDate(infoPtr, &st);
1008       mask = 1 << (st.wDay-1);
1009       length = MONTHCAL_MonthLength(prev_month, date->wYear);
1010
1011       while(st.wDay <= length)
1012       {
1013         MONTHCAL_DrawDay(infoPtr, hdc, &st, infoPtr->monthdayState[0] & mask, ps);
1014         mask <<= 1;
1015         st.wDay++;
1016       }
1017     }
1018
1019     /* draw next month */
1020     if (calIdx == infoPtr->cal_num - 1)
1021     {
1022       st = *date;
1023       st.wDay = 1;
1024       MONTHCAL_GetNextMonth(&st);
1025       MONTHCAL_GetMaxDate(infoPtr, &st_max);
1026       mask = 1;
1027
1028       while(st.wDay <= st_max.wDay)
1029       {
1030         MONTHCAL_DrawDay(infoPtr, hdc, &st, infoPtr->monthdayState[2] & mask, ps);
1031         mask <<= 1;
1032         st.wDay++;
1033       }
1034     }
1035   }
1036
1037   /* 3. current month */
1038   SetTextColor(hdc, infoPtr->colors[MCSC_TEXT]);
1039   st = *date;
1040   st.wDay = 1;
1041   mask = 1;
1042   length = MONTHCAL_MonthLength(date->wMonth, date->wYear);
1043   while(st.wDay <= length)
1044   {
1045     MONTHCAL_DrawDay(infoPtr, hdc, &st, infoPtr->monthdayState[1] & mask, ps);
1046     mask <<= 1;
1047     st.wDay++;
1048   }
1049 }
1050
1051 static void MONTHCAL_Refresh(MONTHCAL_INFO *infoPtr, HDC hdc, const PAINTSTRUCT *ps)
1052 {
1053   COLORREF old_text_clr, old_bk_clr;
1054   HFONT old_font;
1055   INT i;
1056
1057   old_text_clr = SetTextColor(hdc, comctl32_color.clrWindowText);
1058   old_bk_clr   = GetBkColor(hdc);
1059   old_font     = GetCurrentObject(hdc, OBJ_FONT);
1060
1061   for (i = 0; i < infoPtr->cal_num; i++)
1062   {
1063     RECT *title = &infoPtr->calendars[i].title;
1064     RECT r;
1065
1066     /* draw title, redraw all its elements */
1067     if (IntersectRect(&r, &(ps->rcPaint), title))
1068         MONTHCAL_PaintTitle(infoPtr, hdc, ps, i);
1069
1070     /* draw calendar area */
1071     UnionRect(&r, &infoPtr->calendars[i].wdays, &infoPtr->todayrect);
1072     if (IntersectRect(&r, &(ps->rcPaint), &r))
1073         MONTHCAL_PaintCalendar(infoPtr, hdc, ps, i);
1074
1075     /* week numbers */
1076     MONTHCAL_PaintWeeknumbers(infoPtr, hdc, ps, i);
1077   }
1078
1079   /* focus and today rectangle */
1080   MONTHCAL_PaintFocusAndCircle(infoPtr, hdc, ps);
1081
1082   /* today at the bottom left */
1083   MONTHCAL_PaintTodayTitle(infoPtr, hdc, ps);
1084
1085   /* navigation buttons */
1086   MONTHCAL_PaintButton(infoPtr, hdc, DIRECTION_BACKWARD);
1087   MONTHCAL_PaintButton(infoPtr, hdc, DIRECTION_FORWARD);
1088
1089   /* restore context */
1090   SetBkColor(hdc, old_bk_clr);
1091   SelectObject(hdc, old_font);
1092   SetTextColor(hdc, old_text_clr);
1093 }
1094
1095 static LRESULT
1096 MONTHCAL_GetMinReqRect(const MONTHCAL_INFO *infoPtr, RECT *rect)
1097 {
1098   TRACE("rect %p\n", rect);
1099
1100   if(!rect) return FALSE;
1101
1102   *rect = infoPtr->calendars[0].title;
1103   rect->bottom = infoPtr->calendars[0].days.bottom + infoPtr->todayrect.bottom -
1104                  infoPtr->todayrect.top;
1105
1106   AdjustWindowRect(rect, infoPtr->dwStyle, FALSE);
1107
1108   /* minimal rectangle is zero based */
1109   OffsetRect(rect, -rect->left, -rect->top);
1110
1111   TRACE("%s\n", wine_dbgstr_rect(rect));
1112
1113   return TRUE;
1114 }
1115
1116 static COLORREF
1117 MONTHCAL_GetColor(const MONTHCAL_INFO *infoPtr, UINT index)
1118 {
1119   TRACE("%p, %d\n", infoPtr, index);
1120
1121   if (index > MCSC_TRAILINGTEXT) return -1;
1122   return infoPtr->colors[index];
1123 }
1124
1125 static LRESULT
1126 MONTHCAL_SetColor(MONTHCAL_INFO *infoPtr, UINT index, COLORREF color)
1127 {
1128   COLORREF prev;
1129
1130   TRACE("%p, %d: color %08x\n", infoPtr, index, color);
1131
1132   if (index > MCSC_TRAILINGTEXT) return -1;
1133
1134   prev = infoPtr->colors[index];
1135   infoPtr->colors[index] = color;
1136
1137   InvalidateRect(infoPtr->hwndSelf, NULL, index == MCSC_BACKGROUND ? TRUE : FALSE);
1138   return prev;
1139 }
1140
1141 static LRESULT
1142 MONTHCAL_GetMonthDelta(const MONTHCAL_INFO *infoPtr)
1143 {
1144   TRACE("\n");
1145
1146   if(infoPtr->delta)
1147     return infoPtr->delta;
1148   else
1149     return infoPtr->visible;
1150 }
1151
1152
1153 static LRESULT
1154 MONTHCAL_SetMonthDelta(MONTHCAL_INFO *infoPtr, INT delta)
1155 {
1156   INT prev = infoPtr->delta;
1157
1158   TRACE("delta %d\n", delta);
1159
1160   infoPtr->delta = delta;
1161   return prev;
1162 }
1163
1164
1165 static inline LRESULT
1166 MONTHCAL_GetFirstDayOfWeek(const MONTHCAL_INFO *infoPtr)
1167 {
1168   int day;
1169
1170   /* convert from SYSTEMTIME to locale format */
1171   day = (infoPtr->firstDay >= 0) ? (infoPtr->firstDay+6)%7 : infoPtr->firstDay;
1172
1173   return MAKELONG(day, infoPtr->firstDaySet);
1174 }
1175
1176
1177 /* Sets the first day of the week that will appear in the control
1178  *
1179  *
1180  * PARAMETERS:
1181  *  [I] infoPtr : valid pointer to control data
1182  *  [I] day : day number to set as new first day (0 == Monday,...,6 == Sunday)
1183  *
1184  *
1185  * RETURN VALUE:
1186  *  Low word contains previous first day,
1187  *  high word indicates was first day forced with this message before or is
1188  *  locale difined (TRUE - was forced, FALSE - wasn't).
1189  *
1190  * FIXME: this needs to be implemented properly in MONTHCAL_Refresh()
1191  * FIXME: we need more error checking here
1192  */
1193 static LRESULT
1194 MONTHCAL_SetFirstDayOfWeek(MONTHCAL_INFO *infoPtr, INT day)
1195 {
1196   LRESULT prev = MONTHCAL_GetFirstDayOfWeek(infoPtr);
1197   int new_day;
1198
1199   TRACE("%d\n", day);
1200
1201   if(day == -1)
1202   {
1203     WCHAR buf[80];
1204
1205     GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_IFIRSTDAYOFWEEK, buf, countof(buf));
1206     TRACE("%s %d\n", debugstr_w(buf), strlenW(buf));
1207
1208     new_day = atoiW(buf);
1209
1210     infoPtr->firstDaySet = FALSE;
1211   }
1212   else if(day >= 7)
1213   {
1214     new_day = 6; /* max first day allowed */
1215     infoPtr->firstDaySet = TRUE;
1216   }
1217   else
1218   {
1219     /* Native behaviour for that case is broken: invalid date number >31
1220        got displayed at (0,0) position, current month starts always from
1221        (1,0) position. Should be implemented here as well only if there's
1222        nothing else to do. */
1223     if (day < -1)
1224       FIXME("No bug compatibility for day=%d\n", day);
1225
1226     new_day = day;
1227     infoPtr->firstDaySet = TRUE;
1228   }
1229
1230   /* convert from locale to SYSTEMTIME format */
1231   infoPtr->firstDay = (new_day >= 0) ? (++new_day) % 7 : new_day;
1232
1233   InvalidateRect(infoPtr->hwndSelf, NULL, FALSE);
1234
1235   return prev;
1236 }
1237
1238
1239 static LRESULT
1240 MONTHCAL_GetMonthRange(const MONTHCAL_INFO *infoPtr, DWORD flag, SYSTEMTIME *st)
1241 {
1242   TRACE("flag=%d, st=%p\n", flag, st);
1243
1244   if(st)
1245   {
1246     switch (flag) {
1247     case GMR_VISIBLE:
1248     {
1249         st[0] = infoPtr->calendars[0].month;
1250         st[1] = infoPtr->calendars[infoPtr->cal_num-1].month;
1251
1252         if (st[0].wMonth == min_allowed_date.wMonth &&
1253             st[0].wYear  == min_allowed_date.wYear)
1254         {
1255             st[0].wDay = min_allowed_date.wDay;
1256         }
1257         else
1258             st[0].wDay = 1;
1259         MONTHCAL_CalculateDayOfWeek(&st[0], TRUE);
1260
1261         st[1].wDay = MONTHCAL_MonthLength(st[1].wMonth, st[1].wYear);
1262         MONTHCAL_CalculateDayOfWeek(&st[1], TRUE);
1263
1264         return infoPtr->cal_num;
1265     }
1266     case GMR_DAYSTATE:
1267     {
1268         /*FIXME: currently multicalendar feature isn't implemented,
1269                  min date from previous month and max date from next one returned */
1270         MONTHCAL_GetMinDate(infoPtr, &st[0]);
1271         MONTHCAL_GetMaxDate(infoPtr, &st[1]);
1272         break;
1273     }
1274     default:
1275         WARN("Unknown flag value, got %d\n", flag);
1276     }
1277   }
1278
1279   return infoPtr->monthRange;
1280 }
1281
1282
1283 static LRESULT
1284 MONTHCAL_GetMaxTodayWidth(const MONTHCAL_INFO *infoPtr)
1285 {
1286   return(infoPtr->todayrect.right - infoPtr->todayrect.left);
1287 }
1288
1289
1290 static LRESULT
1291 MONTHCAL_SetRange(MONTHCAL_INFO *infoPtr, SHORT limits, SYSTEMTIME *range)
1292 {
1293     FILETIME ft_min, ft_max;
1294
1295     TRACE("%x %p\n", limits, range);
1296
1297     if ((limits & GDTR_MIN && !MONTHCAL_ValidateDate(&range[0])) ||
1298         (limits & GDTR_MAX && !MONTHCAL_ValidateDate(&range[1])))
1299         return FALSE;
1300
1301     if (limits & GDTR_MIN)
1302     {
1303         if (!MONTHCAL_ValidateTime(&range[0]))
1304             MONTHCAL_CopyTime(&infoPtr->todaysDate, &range[0]);
1305
1306         infoPtr->minDate = range[0];
1307         infoPtr->rangeValid |= GDTR_MIN;
1308     }
1309     if (limits & GDTR_MAX)
1310     {
1311         if (!MONTHCAL_ValidateTime(&range[1]))
1312             MONTHCAL_CopyTime(&infoPtr->todaysDate, &range[1]);
1313
1314         infoPtr->maxDate = range[1];
1315         infoPtr->rangeValid |= GDTR_MAX;
1316     }
1317
1318     /* Only one limit set - we are done */
1319     if ((infoPtr->rangeValid & (GDTR_MIN | GDTR_MAX)) != (GDTR_MIN | GDTR_MAX))
1320         return TRUE;
1321
1322     SystemTimeToFileTime(&infoPtr->maxDate, &ft_max);
1323     SystemTimeToFileTime(&infoPtr->minDate, &ft_min);
1324
1325     if (CompareFileTime(&ft_min, &ft_max) >= 0)
1326     {
1327         if ((limits & (GDTR_MIN | GDTR_MAX)) == (GDTR_MIN | GDTR_MAX))
1328         {
1329             /* Native swaps limits only when both limits are being set. */
1330             SYSTEMTIME st_tmp = infoPtr->minDate;
1331             infoPtr->minDate  = infoPtr->maxDate;
1332             infoPtr->maxDate  = st_tmp;
1333         }
1334         else
1335         {
1336             /* reset the other limit */
1337             if (limits & GDTR_MIN) infoPtr->maxDate = st_null;
1338             if (limits & GDTR_MAX) infoPtr->minDate = st_null;
1339             infoPtr->rangeValid &= limits & GDTR_MIN ? ~GDTR_MAX : ~GDTR_MIN;
1340         }
1341     }
1342
1343     return TRUE;
1344 }
1345
1346
1347 static LRESULT
1348 MONTHCAL_GetRange(const MONTHCAL_INFO *infoPtr, SYSTEMTIME *range)
1349 {
1350   TRACE("%p\n", range);
1351
1352   if(!range) return FALSE;
1353
1354   range[1] = infoPtr->maxDate;
1355   range[0] = infoPtr->minDate;
1356
1357   return infoPtr->rangeValid;
1358 }
1359
1360
1361 static LRESULT
1362 MONTHCAL_SetDayState(const MONTHCAL_INFO *infoPtr, INT months, MONTHDAYSTATE *states)
1363 {
1364   TRACE("%p %d %p\n", infoPtr, months, states);
1365   if(months != infoPtr->monthRange) return 0;
1366
1367   memcpy(infoPtr->monthdayState, states, months*sizeof(MONTHDAYSTATE));
1368
1369   return 1;
1370 }
1371
1372 static LRESULT
1373 MONTHCAL_GetCurSel(const MONTHCAL_INFO *infoPtr, SYSTEMTIME *curSel)
1374 {
1375   TRACE("%p\n", curSel);
1376   if(!curSel) return FALSE;
1377   if(infoPtr->dwStyle & MCS_MULTISELECT) return FALSE;
1378
1379   *curSel = infoPtr->minSel;
1380   TRACE("%d/%d/%d\n", curSel->wYear, curSel->wMonth, curSel->wDay);
1381   return TRUE;
1382 }
1383
1384 static LRESULT
1385 MONTHCAL_SetCurSel(MONTHCAL_INFO *infoPtr, SYSTEMTIME *curSel)
1386 {
1387   SYSTEMTIME prev = infoPtr->minSel;
1388   WORD day;
1389
1390   TRACE("%p\n", curSel);
1391   if(!curSel) return FALSE;
1392   if(infoPtr->dwStyle & MCS_MULTISELECT) return FALSE;
1393
1394   if(!MONTHCAL_ValidateDate(curSel)) return FALSE;
1395   /* exit earlier if selection equals current */
1396   if (MONTHCAL_IsDateEqual(&infoPtr->minSel, curSel)) return TRUE;
1397
1398   if(!MONTHCAL_IsDateInValidRange(infoPtr, curSel, FALSE)) return FALSE;
1399
1400   infoPtr->calendars[0].month = *curSel;
1401   infoPtr->minSel = *curSel;
1402   infoPtr->maxSel = *curSel;
1403
1404   /* if selection is still in current month, reduce rectangle */
1405   day = prev.wDay;
1406   prev.wDay = curSel->wDay;
1407   if (MONTHCAL_IsDateEqual(&prev, curSel))
1408   {
1409     RECT r_prev, r_new;
1410
1411     prev.wDay = day;
1412     MONTHCAL_CalcPosFromDay(infoPtr, &prev, &r_prev);
1413     MONTHCAL_CalcPosFromDay(infoPtr, curSel, &r_new);
1414
1415     InvalidateRect(infoPtr->hwndSelf, &r_prev, FALSE);
1416     InvalidateRect(infoPtr->hwndSelf, &r_new,  FALSE);
1417   }
1418   else
1419     InvalidateRect(infoPtr->hwndSelf, NULL, FALSE);
1420
1421   return TRUE;
1422 }
1423
1424
1425 static LRESULT
1426 MONTHCAL_GetMaxSelCount(const MONTHCAL_INFO *infoPtr)
1427 {
1428   return infoPtr->maxSelCount;
1429 }
1430
1431
1432 static LRESULT
1433 MONTHCAL_SetMaxSelCount(MONTHCAL_INFO *infoPtr, INT max)
1434 {
1435   TRACE("%d\n", max);
1436
1437   if(!(infoPtr->dwStyle & MCS_MULTISELECT)) return FALSE;
1438   if(max <= 0) return FALSE;
1439
1440   infoPtr->maxSelCount = max;
1441
1442   return TRUE;
1443 }
1444
1445
1446 static LRESULT
1447 MONTHCAL_GetSelRange(const MONTHCAL_INFO *infoPtr, SYSTEMTIME *range)
1448 {
1449   TRACE("%p\n", range);
1450
1451   if(!range) return FALSE;
1452
1453   if(infoPtr->dwStyle & MCS_MULTISELECT)
1454   {
1455     range[1] = infoPtr->maxSel;
1456     range[0] = infoPtr->minSel;
1457     TRACE("[min,max]=[%d %d]\n", infoPtr->minSel.wDay, infoPtr->maxSel.wDay);
1458     return TRUE;
1459   }
1460
1461   return FALSE;
1462 }
1463
1464
1465 static LRESULT
1466 MONTHCAL_SetSelRange(MONTHCAL_INFO *infoPtr, SYSTEMTIME *range)
1467 {
1468   TRACE("%p\n", range);
1469
1470   if(!range) return FALSE;
1471
1472   if(infoPtr->dwStyle & MCS_MULTISELECT)
1473   {
1474     SYSTEMTIME old_range[2];
1475
1476     /* adjust timestamps */
1477     if(!MONTHCAL_ValidateTime(&range[0]))
1478       MONTHCAL_CopyTime(&infoPtr->todaysDate, &range[0]);
1479     if(!MONTHCAL_ValidateTime(&range[1]))
1480       MONTHCAL_CopyTime(&infoPtr->todaysDate, &range[1]);
1481
1482     /* maximum range exceeded */
1483     if(!MONTHCAL_IsSelRangeValid(infoPtr, &range[0], &range[1], NULL)) return FALSE;
1484
1485     old_range[0] = infoPtr->minSel;
1486     old_range[1] = infoPtr->maxSel;
1487
1488     /* swap if min > max */
1489     if(MONTHCAL_CompareSystemTime(&range[0], &range[1]) <= 0)
1490     {
1491       infoPtr->minSel = range[0];
1492       infoPtr->maxSel = range[1];
1493     }
1494     else
1495     {
1496       infoPtr->minSel = range[1];
1497       infoPtr->maxSel = range[0];
1498     }
1499     infoPtr->calendars[0].month = infoPtr->minSel;
1500
1501     /* update day of week */
1502     MONTHCAL_CalculateDayOfWeek(&infoPtr->minSel, TRUE);
1503     MONTHCAL_CalculateDayOfWeek(&infoPtr->maxSel, TRUE);
1504
1505     /* redraw if bounds changed */
1506     /* FIXME: no actual need to redraw everything */
1507     if(!MONTHCAL_IsDateEqual(&old_range[0], &range[0]) ||
1508        !MONTHCAL_IsDateEqual(&old_range[1], &range[1]))
1509     {
1510        InvalidateRect(infoPtr->hwndSelf, NULL, FALSE);
1511     }
1512
1513     TRACE("[min,max]=[%d %d]\n", infoPtr->minSel.wDay, infoPtr->maxSel.wDay);
1514     return TRUE;
1515   }
1516
1517   return FALSE;
1518 }
1519
1520
1521 static LRESULT
1522 MONTHCAL_GetToday(const MONTHCAL_INFO *infoPtr, SYSTEMTIME *today)
1523 {
1524   TRACE("%p\n", today);
1525
1526   if(!today) return FALSE;
1527   *today = infoPtr->todaysDate;
1528   return TRUE;
1529 }
1530
1531 /* Internal helper for MCM_SETTODAY handler and auto update timer handler
1532  *
1533  * RETURN VALUE
1534  *
1535  *  TRUE  - today date changed
1536  *  FALSE - today date isn't changed
1537  */
1538 static BOOL
1539 MONTHCAL_UpdateToday(MONTHCAL_INFO *infoPtr, const SYSTEMTIME *today)
1540 {
1541   RECT new_r, old_r;
1542
1543   if(MONTHCAL_IsDateEqual(today, &infoPtr->todaysDate)) return FALSE;
1544
1545   MONTHCAL_CalcPosFromDay(infoPtr, &infoPtr->todaysDate, &old_r);
1546   MONTHCAL_CalcPosFromDay(infoPtr, today, &new_r);
1547
1548   infoPtr->todaysDate = *today;
1549
1550   /* only two days need redrawing */
1551   InvalidateRect(infoPtr->hwndSelf, &old_r, FALSE);
1552   InvalidateRect(infoPtr->hwndSelf, &new_r, FALSE);
1553   return TRUE;
1554 }
1555
1556 /* MCM_SETTODAT handler */
1557 static LRESULT
1558 MONTHCAL_SetToday(MONTHCAL_INFO *infoPtr, const SYSTEMTIME *today)
1559 {
1560   TRACE("%p\n", today);
1561
1562   if(!today) return FALSE;
1563
1564   /* remember if date was set successfully */
1565   if(MONTHCAL_UpdateToday(infoPtr, today)) infoPtr->todaySet = TRUE;
1566
1567   return TRUE;
1568 }
1569
1570 /* returns calendar index containing specified point, or -1 if it's background */
1571 static INT MONTHCAL_GetCalendarFromPoint(const MONTHCAL_INFO *infoPtr, const POINT *pt)
1572 {
1573   RECT r;
1574   INT i;
1575
1576   for (i = 0; i < infoPtr->cal_num; i++)
1577   {
1578      /* whole bounding rectangle allows some optimization to compute */
1579      r.left   = infoPtr->calendars[i].title.left;
1580      r.top    = infoPtr->calendars[i].title.top;
1581      r.bottom = infoPtr->calendars[i].days.bottom;
1582      r.right  = infoPtr->calendars[i].days.right;
1583
1584      if (PtInRect(&r, *pt)) return i;
1585   }
1586
1587   return -1;
1588 }
1589
1590 static inline UINT fill_hittest_info(const MCHITTESTINFO *src, MCHITTESTINFO *dest)
1591 {
1592   dest->uHit = src->uHit;
1593   dest->st = src->st;
1594
1595   if (dest->cbSize == sizeof(MCHITTESTINFO))
1596     memcpy(&dest->rc, &src->rc, sizeof(MCHITTESTINFO) - MCHITTESTINFO_V1_SIZE);
1597
1598   return src->uHit;
1599 }
1600
1601 static LRESULT
1602 MONTHCAL_HitTest(const MONTHCAL_INFO *infoPtr, MCHITTESTINFO *lpht)
1603 {
1604   INT day, wday, wnum, calIdx;
1605   MCHITTESTINFO htinfo;
1606   SYSTEMTIME ht_month;
1607   UINT x, y;
1608
1609   if(!lpht || lpht->cbSize < MCHITTESTINFO_V1_SIZE) return -1;
1610
1611   x = lpht->pt.x;
1612   y = lpht->pt.y;
1613
1614   htinfo.st = st_null;
1615
1616   /* we should preserve passed fields if hit area doesn't need them */
1617   if (lpht->cbSize == sizeof(MCHITTESTINFO))
1618     memcpy(&htinfo.rc, &lpht->rc, sizeof(MCHITTESTINFO) - MCHITTESTINFO_V1_SIZE);
1619
1620   /* Comment in for debugging...
1621   TRACE("%d %d wd[%d %d %d %d] d[%d %d %d %d] t[%d %d %d %d] wn[%d %d %d %d]\n", x, y,
1622         infoPtr->wdays.left, infoPtr->wdays.right,
1623         infoPtr->wdays.top, infoPtr->wdays.bottom,
1624         infoPtr->days.left, infoPtr->days.right,
1625         infoPtr->days.top, infoPtr->days.bottom,
1626         infoPtr->todayrect.left, infoPtr->todayrect.right,
1627         infoPtr->todayrect.top, infoPtr->todayrect.bottom,
1628         infoPtr->weeknums.left, infoPtr->weeknums.right,
1629         infoPtr->weeknums.top, infoPtr->weeknums.bottom);
1630   */
1631
1632   /* guess in what calendar we are */
1633   calIdx = MONTHCAL_GetCalendarFromPoint(infoPtr, &lpht->pt);
1634   if (calIdx == -1)
1635   {
1636     if (PtInRect(&infoPtr->todayrect, lpht->pt))
1637     {
1638       htinfo.uHit = MCHT_TODAYLINK;
1639       htinfo.rc = infoPtr->todayrect;
1640     }
1641     else
1642       /* outside of calendar area? What's left must be background :-) */
1643       htinfo.uHit = MCHT_CALENDARBK;
1644
1645     return fill_hittest_info(&htinfo, lpht);
1646   }
1647
1648   ht_month = infoPtr->calendars[calIdx].month;
1649
1650   /* are we in the header? */
1651   if (PtInRect(&infoPtr->calendars[calIdx].title, lpht->pt)) {
1652     /* FIXME: buttons hittesting could be optimized cause maximum
1653               two calendars have buttons */
1654     if (calIdx == 0 && PtInRect(&infoPtr->titlebtnprev, lpht->pt))
1655     {
1656       htinfo.uHit = MCHT_TITLEBTNPREV;
1657       htinfo.rc = infoPtr->titlebtnprev;
1658     }
1659     else if (PtInRect(&infoPtr->titlebtnnext, lpht->pt))
1660     {
1661       htinfo.uHit = MCHT_TITLEBTNNEXT;
1662       htinfo.rc = infoPtr->titlebtnnext;
1663     }
1664     else if (PtInRect(&infoPtr->calendars[calIdx].titlemonth, lpht->pt))
1665     {
1666       htinfo.uHit = MCHT_TITLEMONTH;
1667       htinfo.rc = infoPtr->calendars[calIdx].titlemonth;
1668       htinfo.iOffset = calIdx;
1669     }
1670     else if (PtInRect(&infoPtr->calendars[calIdx].titleyear, lpht->pt))
1671     {
1672       htinfo.uHit = MCHT_TITLEYEAR;
1673       htinfo.rc = infoPtr->calendars[calIdx].titleyear;
1674       htinfo.iOffset = calIdx;
1675     }
1676     else
1677     {
1678       htinfo.uHit = MCHT_TITLE;
1679       htinfo.rc = infoPtr->calendars[calIdx].title;
1680       htinfo.iOffset = calIdx;
1681     }
1682
1683     return fill_hittest_info(&htinfo, lpht);
1684   }
1685
1686   /* days area (including week days and week numbers */
1687   day = MONTHCAL_CalcDayFromPos(infoPtr, x, y, &wday, &wnum);
1688   if (PtInRect(&infoPtr->calendars[calIdx].wdays, lpht->pt))
1689   {
1690     htinfo.uHit = MCHT_CALENDARDAY;
1691     htinfo.iOffset = calIdx;
1692     htinfo.st.wYear  = ht_month.wYear;
1693     htinfo.st.wMonth = (day < 1) ? ht_month.wMonth -1 : ht_month.wMonth;
1694     htinfo.st.wDay   = (day < 1) ?
1695       MONTHCAL_MonthLength(ht_month.wMonth-1, ht_month.wYear) - day : day;
1696
1697     MONTHCAL_CalcDayXY(infoPtr, &htinfo.st, &htinfo.iCol, &htinfo.iRow);
1698   }
1699   else if(PtInRect(&infoPtr->calendars[calIdx].weeknums, lpht->pt))
1700   {
1701     htinfo.uHit = MCHT_CALENDARWEEKNUM;
1702     htinfo.st.wYear  = ht_month.wYear;
1703     htinfo.iOffset = calIdx;
1704
1705     if (day < 1)
1706     {
1707       htinfo.st.wMonth = ht_month.wMonth - 1;
1708       htinfo.st.wDay = MONTHCAL_MonthLength(ht_month.wMonth-1, ht_month.wYear) - day;
1709     }
1710     else if (day > MONTHCAL_MonthLength(ht_month.wMonth, ht_month.wYear))
1711     {
1712       htinfo.st.wMonth = ht_month.wMonth + 1;
1713       htinfo.st.wDay = day - MONTHCAL_MonthLength(ht_month.wMonth, ht_month.wYear);
1714     }
1715     else
1716     {
1717       htinfo.st.wMonth = ht_month.wMonth;
1718       htinfo.st.wDay = day;
1719     }
1720   }
1721   else if(PtInRect(&infoPtr->calendars[calIdx].days, lpht->pt))
1722   {
1723       htinfo.iOffset = calIdx;
1724       htinfo.st.wYear  = ht_month.wYear;
1725       htinfo.st.wMonth = ht_month.wMonth;
1726       if (day < 1)
1727       {
1728           htinfo.uHit = MCHT_CALENDARDATEPREV;
1729           MONTHCAL_GetPrevMonth(&htinfo.st);
1730           htinfo.st.wDay = MONTHCAL_MonthLength(lpht->st.wMonth, lpht->st.wYear) + day;
1731       }
1732       else if (day > MONTHCAL_MonthLength(ht_month.wMonth, ht_month.wYear))
1733       {
1734           htinfo.uHit = MCHT_CALENDARDATENEXT;
1735           MONTHCAL_GetNextMonth(&htinfo.st);
1736           htinfo.st.wDay = day - MONTHCAL_MonthLength(ht_month.wMonth, ht_month.wYear);
1737       }
1738       else
1739       {
1740         htinfo.uHit = MCHT_CALENDARDATE;
1741         htinfo.st.wDay = day;
1742       }
1743
1744       MONTHCAL_CalcDayXY(infoPtr, &htinfo.st, &htinfo.iCol, &htinfo.iRow);
1745       MONTHCAL_CalcDayRect(infoPtr, &htinfo.rc, htinfo.iCol, htinfo.iRow);
1746       /* always update day of week */
1747       MONTHCAL_CalculateDayOfWeek(&htinfo.st, TRUE);
1748   }
1749
1750   return fill_hittest_info(&htinfo, lpht);
1751 }
1752
1753 /* MCN_GETDAYSTATE notification helper */
1754 static void MONTHCAL_NotifyDayState(MONTHCAL_INFO *infoPtr)
1755 {
1756   if(infoPtr->dwStyle & MCS_DAYSTATE) {
1757     NMDAYSTATE nmds;
1758
1759     nmds.nmhdr.hwndFrom = infoPtr->hwndSelf;
1760     nmds.nmhdr.idFrom   = GetWindowLongPtrW(infoPtr->hwndSelf, GWLP_ID);
1761     nmds.nmhdr.code     = MCN_GETDAYSTATE;
1762     nmds.cDayState      = infoPtr->monthRange;
1763     nmds.prgDayState    = Alloc(infoPtr->monthRange * sizeof(MONTHDAYSTATE));
1764
1765     nmds.stStart = infoPtr->todaysDate;
1766     nmds.stStart.wYear  = infoPtr->minSel.wYear;
1767     nmds.stStart.wMonth = infoPtr->minSel.wMonth;
1768     nmds.stStart.wDay = 1;
1769
1770     SendMessageW(infoPtr->hwndNotify, WM_NOTIFY, nmds.nmhdr.idFrom, (LPARAM)&nmds);
1771     memcpy(infoPtr->monthdayState, nmds.prgDayState, infoPtr->monthRange*sizeof(MONTHDAYSTATE));
1772
1773     Free(nmds.prgDayState);
1774   }
1775 }
1776
1777 /* no valid range check performed */
1778 static void MONTHCAL_Scroll(MONTHCAL_INFO *infoPtr, INT delta)
1779 {
1780   INT i, selIdx = -1;
1781
1782   for(i = 0; i < infoPtr->cal_num; i++)
1783   {
1784     /* save selection position to shift it later */
1785     if (selIdx == -1 && MONTHCAL_CompareMonths(&infoPtr->minSel, &infoPtr->calendars[i].month) == 0)
1786       selIdx = i;
1787
1788     MONTHCAL_GetMonth(&infoPtr->calendars[i].month, delta);
1789   }
1790
1791   /* selection is always shifted to first calendar */
1792   if(infoPtr->dwStyle & MCS_MULTISELECT)
1793   {
1794     SYSTEMTIME range[2];
1795
1796     MONTHCAL_GetSelRange(infoPtr, range);
1797     MONTHCAL_GetMonth(&range[0], delta - selIdx);
1798     MONTHCAL_GetMonth(&range[1], delta - selIdx);
1799     MONTHCAL_SetSelRange(infoPtr, range);
1800   }
1801   else
1802   {
1803     SYSTEMTIME st = infoPtr->minSel;
1804
1805     MONTHCAL_GetMonth(&st, delta - selIdx);
1806     MONTHCAL_SetCurSel(infoPtr, &st);
1807   }
1808 }
1809
1810 static void MONTHCAL_GoToMonth(MONTHCAL_INFO *infoPtr, enum nav_direction direction)
1811 {
1812   INT delta = infoPtr->delta ? infoPtr->delta : infoPtr->cal_num;
1813   SYSTEMTIME st;
1814
1815   TRACE("%s\n", direction == DIRECTION_BACKWARD ? "back" : "fwd");
1816
1817   /* check if change allowed by range set */
1818   if(direction == DIRECTION_BACKWARD)
1819   {
1820     st = infoPtr->calendars[0].month;
1821     MONTHCAL_GetMonth(&st, -delta);
1822   }
1823   else
1824   {
1825     st = infoPtr->calendars[infoPtr->cal_num-1].month;
1826     MONTHCAL_GetMonth(&st, delta);
1827   }
1828
1829   if(!MONTHCAL_IsDateInValidRange(infoPtr, &st, FALSE)) return;
1830
1831   MONTHCAL_Scroll(infoPtr, direction == DIRECTION_BACKWARD ? -delta : delta);
1832   MONTHCAL_NotifyDayState(infoPtr);
1833   MONTHCAL_NotifySelectionChange(infoPtr);
1834 }
1835
1836 static LRESULT
1837 MONTHCAL_RButtonUp(MONTHCAL_INFO *infoPtr, LPARAM lParam)
1838 {
1839   static const WCHAR todayW[] = { 'G','o',' ','t','o',' ','T','o','d','a','y',':',0 };
1840   HMENU hMenu;
1841   POINT menupoint;
1842   WCHAR buf[32];
1843
1844   hMenu = CreatePopupMenu();
1845   if (!LoadStringW(COMCTL32_hModule, IDM_GOTODAY, buf, countof(buf)))
1846   {
1847       WARN("Can't load resource\n");
1848       strcpyW(buf, todayW);
1849   }
1850   AppendMenuW(hMenu, MF_STRING|MF_ENABLED, 1, buf);
1851   menupoint.x = (short)LOWORD(lParam);
1852   menupoint.y = (short)HIWORD(lParam);
1853   ClientToScreen(infoPtr->hwndSelf, &menupoint);
1854   if( TrackPopupMenu(hMenu, TPM_RIGHTBUTTON | TPM_NONOTIFY | TPM_RETURNCMD,
1855                      menupoint.x, menupoint.y, 0, infoPtr->hwndSelf, NULL))
1856   {
1857       infoPtr->calendars[0].month = infoPtr->todaysDate;
1858       infoPtr->minSel = infoPtr->todaysDate;
1859       infoPtr->maxSel = infoPtr->todaysDate;
1860       InvalidateRect(infoPtr->hwndSelf, NULL, FALSE);
1861   }
1862
1863   return 0;
1864 }
1865
1866 /***
1867  * DESCRIPTION:
1868  * Subclassed edit control windproc function
1869  *
1870  * PARAMETER(S):
1871  * [I] hwnd : the edit window handle
1872  * [I] uMsg : the message that is to be processed
1873  * [I] wParam : first message parameter
1874  * [I] lParam : second message parameter
1875  *
1876  */
1877 static LRESULT CALLBACK EditWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
1878 {
1879     MONTHCAL_INFO *infoPtr = (MONTHCAL_INFO *)GetWindowLongPtrW(GetParent(hwnd), 0);
1880
1881     TRACE("(hwnd=%p, uMsg=%x, wParam=%lx, lParam=%lx)\n",
1882           hwnd, uMsg, wParam, lParam);
1883
1884     switch (uMsg)
1885     {
1886         case WM_GETDLGCODE:
1887           return DLGC_WANTARROWS | DLGC_WANTALLKEYS;
1888
1889         case WM_DESTROY:
1890         {
1891             WNDPROC editProc = infoPtr->EditWndProc;
1892             infoPtr->EditWndProc = NULL;
1893             SetWindowLongPtrW(hwnd, GWLP_WNDPROC, (DWORD_PTR)editProc);
1894             return CallWindowProcW(editProc, hwnd, uMsg, wParam, lParam);
1895         }
1896
1897         case WM_KILLFOCUS:
1898             break;
1899
1900         case WM_KEYDOWN:
1901             if ((VK_ESCAPE == (INT)wParam) || (VK_RETURN == (INT)wParam))
1902                 break;
1903
1904         default:
1905             return CallWindowProcW(infoPtr->EditWndProc, hwnd, uMsg, wParam, lParam);
1906     }
1907
1908     SendMessageW(infoPtr->hWndYearUpDown, WM_CLOSE, 0, 0);
1909     SendMessageW(hwnd, WM_CLOSE, 0, 0);
1910     return 0;
1911 }
1912
1913 /* creates updown control and edit box */
1914 static void MONTHCAL_EditYear(MONTHCAL_INFO *infoPtr, INT calIdx)
1915 {
1916     RECT *rc = &infoPtr->calendars[calIdx].titleyear;
1917     RECT *title = &infoPtr->calendars[calIdx].title;
1918
1919     infoPtr->hWndYearEdit =
1920         CreateWindowExW(0, WC_EDITW, 0, WS_VISIBLE | WS_CHILD | ES_READONLY,
1921                         rc->left + 3, (title->bottom + title->top - infoPtr->textHeight) / 2,
1922                         rc->right - rc->left + 4,
1923                         infoPtr->textHeight, infoPtr->hwndSelf,
1924                         NULL, NULL, NULL);
1925
1926     SendMessageW(infoPtr->hWndYearEdit, WM_SETFONT, (WPARAM)infoPtr->hBoldFont, TRUE);
1927
1928     infoPtr->hWndYearUpDown =
1929         CreateWindowExW(0, UPDOWN_CLASSW, 0,
1930                         WS_VISIBLE | WS_CHILD | UDS_SETBUDDYINT | UDS_NOTHOUSANDS | UDS_ARROWKEYS,
1931                         rc->right + 7, (title->bottom + title->top - infoPtr->textHeight) / 2,
1932                         18, infoPtr->textHeight, infoPtr->hwndSelf,
1933                         NULL, NULL, NULL);
1934
1935     /* attach edit box */
1936     SendMessageW(infoPtr->hWndYearUpDown, UDM_SETRANGE, 0,
1937                  MAKELONG(max_allowed_date.wYear, min_allowed_date.wYear));
1938     SendMessageW(infoPtr->hWndYearUpDown, UDM_SETBUDDY, (WPARAM)infoPtr->hWndYearEdit, 0);
1939     SendMessageW(infoPtr->hWndYearUpDown, UDM_SETPOS, 0, infoPtr->calendars[calIdx].month.wYear);
1940
1941     /* subclass edit box */
1942     infoPtr->EditWndProc = (WNDPROC)SetWindowLongPtrW(infoPtr->hWndYearEdit,
1943                                   GWLP_WNDPROC, (DWORD_PTR)EditWndProc);
1944
1945     SetFocus(infoPtr->hWndYearEdit);
1946 }
1947
1948 static LRESULT
1949 MONTHCAL_LButtonDown(MONTHCAL_INFO *infoPtr, LPARAM lParam)
1950 {
1951   MCHITTESTINFO ht;
1952   DWORD hit;
1953
1954   /* Actually we don't need input focus for calendar, this is used to kill
1955      year updown and its buddy edit box */
1956   if (IsWindow(infoPtr->hWndYearUpDown))
1957   {
1958       SetFocus(infoPtr->hwndSelf);
1959       return 0;
1960   }
1961
1962   SetCapture(infoPtr->hwndSelf);
1963
1964   ht.cbSize = sizeof(MCHITTESTINFO);
1965   ht.pt.x = (short)LOWORD(lParam);
1966   ht.pt.y = (short)HIWORD(lParam);
1967
1968   hit = MONTHCAL_HitTest(infoPtr, &ht);
1969
1970   TRACE("%x at (%d, %d)\n", hit, ht.pt.x, ht.pt.y);
1971
1972   switch(hit)
1973   {
1974   case MCHT_TITLEBTNNEXT:
1975     MONTHCAL_GoToMonth(infoPtr, DIRECTION_FORWARD);
1976     infoPtr->status = MC_NEXTPRESSED;
1977     SetTimer(infoPtr->hwndSelf, MC_PREVNEXTMONTHTIMER, MC_PREVNEXTMONTHDELAY, 0);
1978     InvalidateRect(infoPtr->hwndSelf, NULL, FALSE);
1979     return 0;
1980
1981   case MCHT_TITLEBTNPREV:
1982     MONTHCAL_GoToMonth(infoPtr, DIRECTION_BACKWARD);
1983     infoPtr->status = MC_PREVPRESSED;
1984     SetTimer(infoPtr->hwndSelf, MC_PREVNEXTMONTHTIMER, MC_PREVNEXTMONTHDELAY, 0);
1985     InvalidateRect(infoPtr->hwndSelf, NULL, FALSE);
1986     return 0;
1987
1988   case MCHT_TITLEMONTH:
1989   {
1990     HMENU hMenu = CreatePopupMenu();
1991     WCHAR buf[32];
1992     POINT menupoint;
1993     INT i;
1994
1995     for (i = 0; i < 12; i++)
1996     {
1997         GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SMONTHNAME1+i, buf, countof(buf));
1998         AppendMenuW(hMenu, MF_STRING|MF_ENABLED, i + 1, buf);
1999     }
2000     menupoint.x = ht.pt.x;
2001     menupoint.y = ht.pt.y;
2002     ClientToScreen(infoPtr->hwndSelf, &menupoint);
2003     i = TrackPopupMenu(hMenu,TPM_LEFTALIGN | TPM_NONOTIFY | TPM_RIGHTBUTTON | TPM_RETURNCMD,
2004                        menupoint.x, menupoint.y, 0, infoPtr->hwndSelf, NULL);
2005
2006     if ((i > 0) && (i < 13) && infoPtr->calendars[ht.iOffset].month.wMonth != i)
2007     {
2008         INT delta = i - infoPtr->calendars[ht.iOffset].month.wMonth;
2009         SYSTEMTIME st;
2010
2011         /* check if change allowed by range set */
2012         st = delta < 0 ? infoPtr->calendars[0].month :
2013                          infoPtr->calendars[infoPtr->cal_num-1].month;
2014         MONTHCAL_GetMonth(&st, delta);
2015
2016         if (MONTHCAL_IsDateInValidRange(infoPtr, &st, FALSE))
2017         {
2018             MONTHCAL_Scroll(infoPtr, delta);
2019             MONTHCAL_NotifyDayState(infoPtr);
2020             MONTHCAL_NotifySelectionChange(infoPtr);
2021             InvalidateRect(infoPtr->hwndSelf, NULL, FALSE);
2022         }
2023     }
2024     return 0;
2025   }
2026   case MCHT_TITLEYEAR:
2027   {
2028     MONTHCAL_EditYear(infoPtr, ht.iOffset);
2029     return 0;
2030   }
2031   case MCHT_TODAYLINK:
2032   {
2033     infoPtr->calendars[0].month = infoPtr->todaysDate;
2034     infoPtr->minSel = infoPtr->todaysDate;
2035     infoPtr->maxSel = infoPtr->todaysDate;
2036     InvalidateRect(infoPtr->hwndSelf, NULL, FALSE);
2037
2038     MONTHCAL_NotifySelectionChange(infoPtr);
2039     MONTHCAL_NotifySelect(infoPtr);
2040     return 0;
2041   }
2042   case MCHT_CALENDARDATENEXT:
2043   case MCHT_CALENDARDATEPREV:
2044   case MCHT_CALENDARDATE:
2045   {
2046     SYSTEMTIME st[2];
2047
2048     MONTHCAL_CopyDate(&ht.st, &infoPtr->firstSel);
2049
2050     st[0] = st[1] = ht.st;
2051     /* clear selection range */
2052     MONTHCAL_SetSelRange(infoPtr, st);
2053
2054     infoPtr->status = MC_SEL_LBUTDOWN;
2055     MONTHCAL_SetDayFocus(infoPtr, &ht.st);
2056     return 0;
2057   }
2058   }
2059
2060   return 1;
2061 }
2062
2063
2064 static LRESULT
2065 MONTHCAL_LButtonUp(MONTHCAL_INFO *infoPtr, LPARAM lParam)
2066 {
2067   NMHDR nmhdr;
2068   MCHITTESTINFO ht;
2069   DWORD hit;
2070
2071   TRACE("\n");
2072
2073   if(infoPtr->status & (MC_PREVPRESSED | MC_NEXTPRESSED)) {
2074     RECT *r;
2075
2076     KillTimer(infoPtr->hwndSelf, MC_PREVNEXTMONTHTIMER);
2077     r = infoPtr->status & MC_PREVPRESSED ? &infoPtr->titlebtnprev : &infoPtr->titlebtnnext;
2078     infoPtr->status &= ~(MC_PREVPRESSED | MC_NEXTPRESSED);
2079
2080     InvalidateRect(infoPtr->hwndSelf, r, FALSE);
2081   }
2082
2083   ReleaseCapture();
2084
2085   /* always send NM_RELEASEDCAPTURE notification */
2086   nmhdr.hwndFrom = infoPtr->hwndSelf;
2087   nmhdr.idFrom   = GetWindowLongPtrW(infoPtr->hwndSelf, GWLP_ID);
2088   nmhdr.code     = NM_RELEASEDCAPTURE;
2089   TRACE("Sent notification from %p to %p\n", infoPtr->hwndSelf, infoPtr->hwndNotify);
2090
2091   SendMessageW(infoPtr->hwndNotify, WM_NOTIFY, nmhdr.idFrom, (LPARAM)&nmhdr);
2092
2093   if(!(infoPtr->status & MC_SEL_LBUTDOWN)) return 0;
2094
2095   ht.cbSize = sizeof(MCHITTESTINFO);
2096   ht.pt.x = (short)LOWORD(lParam);
2097   ht.pt.y = (short)HIWORD(lParam);
2098   hit = MONTHCAL_HitTest(infoPtr, &ht);
2099
2100   infoPtr->status = MC_SEL_LBUTUP;
2101   MONTHCAL_SetDayFocus(infoPtr, NULL);
2102
2103   if((hit & MCHT_CALENDARDATE) == MCHT_CALENDARDATE)
2104   {
2105     SYSTEMTIME sel = infoPtr->minSel;
2106
2107     /* will be invalidated here */
2108     MONTHCAL_SetCurSel(infoPtr, &ht.st);
2109
2110     /* send MCN_SELCHANGE only if new date selected */
2111     if (!MONTHCAL_IsDateEqual(&sel, &ht.st))
2112         MONTHCAL_NotifySelectionChange(infoPtr);
2113
2114     MONTHCAL_NotifySelect(infoPtr);
2115   }
2116
2117   return 0;
2118 }
2119
2120
2121 static LRESULT
2122 MONTHCAL_Timer(MONTHCAL_INFO *infoPtr, WPARAM id)
2123 {
2124   TRACE("%ld\n", id);
2125
2126   switch(id) {
2127   case MC_PREVNEXTMONTHTIMER:
2128     if(infoPtr->status & MC_NEXTPRESSED) MONTHCAL_GoToMonth(infoPtr, DIRECTION_FORWARD);
2129     if(infoPtr->status & MC_PREVPRESSED) MONTHCAL_GoToMonth(infoPtr, DIRECTION_BACKWARD);
2130     InvalidateRect(infoPtr->hwndSelf, NULL, FALSE);
2131     break;
2132   case MC_TODAYUPDATETIMER:
2133   {
2134     SYSTEMTIME st;
2135
2136     if(infoPtr->todaySet) return 0;
2137
2138     GetLocalTime(&st);
2139     MONTHCAL_UpdateToday(infoPtr, &st);
2140
2141     /* notification sent anyway */
2142     MONTHCAL_NotifySelectionChange(infoPtr);
2143
2144     return 0;
2145   }
2146   default:
2147     ERR("got unknown timer %ld\n", id);
2148     break;
2149   }
2150
2151   return 0;
2152 }
2153
2154
2155 static LRESULT
2156 MONTHCAL_MouseMove(MONTHCAL_INFO *infoPtr, LPARAM lParam)
2157 {
2158   MCHITTESTINFO ht;
2159   SYSTEMTIME st_ht;
2160   INT hit;
2161   RECT r;
2162
2163   if(!(infoPtr->status & MC_SEL_LBUTDOWN)) return 0;
2164
2165   ht.cbSize = sizeof(MCHITTESTINFO);
2166   ht.pt.x = (short)LOWORD(lParam);
2167   ht.pt.y = (short)HIWORD(lParam);
2168
2169   hit = MONTHCAL_HitTest(infoPtr, &ht);
2170
2171   /* not on the calendar date numbers? bail out */
2172   TRACE("hit:%x\n",hit);
2173   if((hit & MCHT_CALENDARDATE) != MCHT_CALENDARDATE)
2174   {
2175     MONTHCAL_SetDayFocus(infoPtr, NULL);
2176     return 0;
2177   }
2178
2179   st_ht = ht.st;
2180
2181   /* if pointer is over focused day still there's nothing to do */
2182   if(!MONTHCAL_SetDayFocus(infoPtr, &ht.st)) return 0;
2183
2184   MONTHCAL_CalcPosFromDay(infoPtr, &ht.st, &r);
2185
2186   if(infoPtr->dwStyle & MCS_MULTISELECT) {
2187     SYSTEMTIME st[2];
2188
2189     MONTHCAL_GetSelRange(infoPtr, st);
2190
2191     /* If we're still at the first selected date and range is empty, return.
2192        If range isn't empty we should change range to a single firstSel */
2193     if(MONTHCAL_IsDateEqual(&infoPtr->firstSel, &st_ht) &&
2194        MONTHCAL_IsDateEqual(&st[0], &st[1])) goto done;
2195
2196     MONTHCAL_IsSelRangeValid(infoPtr, &st_ht, &infoPtr->firstSel, &st_ht);
2197
2198     st[0] = infoPtr->firstSel;
2199     /* we should overwrite timestamp here */
2200     MONTHCAL_CopyDate(&st_ht, &st[1]);
2201
2202     /* bounds will be swapped here if needed */
2203     MONTHCAL_SetSelRange(infoPtr, st);
2204
2205     return 0;
2206   }
2207
2208 done:
2209
2210   /* FIXME: this should specify a rectangle containing only the days that changed
2211      using InvalidateRect */
2212   InvalidateRect(infoPtr->hwndSelf, NULL, FALSE);
2213
2214   return 0;
2215 }
2216
2217
2218 static LRESULT
2219 MONTHCAL_Paint(MONTHCAL_INFO *infoPtr, HDC hdc_paint)
2220 {
2221   HDC hdc;
2222   PAINTSTRUCT ps;
2223
2224   if (hdc_paint)
2225   {
2226     GetClientRect(infoPtr->hwndSelf, &ps.rcPaint);
2227     hdc = hdc_paint;
2228   }
2229   else
2230     hdc = BeginPaint(infoPtr->hwndSelf, &ps);
2231
2232   MONTHCAL_Refresh(infoPtr, hdc, &ps);
2233   if (!hdc_paint) EndPaint(infoPtr->hwndSelf, &ps);
2234   return 0;
2235 }
2236
2237 static LRESULT
2238 MONTHCAL_EraseBkgnd(const MONTHCAL_INFO *infoPtr, HDC hdc)
2239 {
2240   HBRUSH hbr;
2241   RECT rc;
2242
2243   if (!GetClipBox(hdc, &rc)) return FALSE;
2244
2245   /* fill background */
2246   hbr = CreateSolidBrush (infoPtr->colors[MCSC_BACKGROUND]);
2247   FillRect(hdc, &rc, hbr);
2248   DeleteObject(hbr);
2249
2250   return TRUE;
2251 }
2252
2253 static LRESULT
2254 MONTHCAL_PrintClient(MONTHCAL_INFO *infoPtr, HDC hdc, DWORD options)
2255 {
2256   FIXME("Partial Stub: (hdc=%p options=0x%08x)\n", hdc, options);
2257
2258   if ((options & PRF_CHECKVISIBLE) && !IsWindowVisible(infoPtr->hwndSelf))
2259       return 0;
2260
2261   if (options & PRF_ERASEBKGND)
2262       MONTHCAL_EraseBkgnd(infoPtr, hdc);
2263
2264   if (options & PRF_CLIENT)
2265       MONTHCAL_Paint(infoPtr, hdc);
2266
2267   return 0;
2268 }
2269
2270 static LRESULT
2271 MONTHCAL_SetFocus(const MONTHCAL_INFO *infoPtr)
2272 {
2273   TRACE("\n");
2274
2275   InvalidateRect(infoPtr->hwndSelf, NULL, FALSE);
2276
2277   return 0;
2278 }
2279
2280 /* sets the size information */
2281 static void MONTHCAL_UpdateSize(MONTHCAL_INFO *infoPtr)
2282 {
2283   static const WCHAR O0W[] = { '0','0',0 };
2284   HDC hdc = GetDC(infoPtr->hwndSelf);
2285   RECT *title=&infoPtr->calendars[0].title;
2286   RECT *prev=&infoPtr->titlebtnprev;
2287   RECT *next=&infoPtr->titlebtnnext;
2288   RECT *titlemonth=&infoPtr->calendars[0].titlemonth;
2289   RECT *titleyear=&infoPtr->calendars[0].titleyear;
2290   RECT *wdays=&infoPtr->calendars[0].wdays;
2291   RECT *weeknumrect=&infoPtr->calendars[0].weeknums;
2292   RECT *days=&infoPtr->calendars[0].days;
2293   RECT *todayrect=&infoPtr->todayrect;
2294   SIZE size, sz;
2295   TEXTMETRICW tm;
2296   HFONT currentFont;
2297   INT xdiv, dx, dy, i;
2298   RECT rcClient;
2299   WCHAR buff[80];
2300
2301   GetClientRect(infoPtr->hwndSelf, &rcClient);
2302
2303   currentFont = SelectObject(hdc, infoPtr->hFont);
2304
2305   /* get the height and width of each day's text */
2306   GetTextMetricsW(hdc, &tm);
2307   infoPtr->textHeight = tm.tmHeight + tm.tmExternalLeading + tm.tmInternalLeading;
2308
2309   /* find largest abbreviated day name for current locale */
2310   size.cx = sz.cx = 0;
2311   for (i = 0; i < 7; i++)
2312   {
2313       if(GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SABBREVDAYNAME1 + i,
2314                         buff, countof(buff)))
2315       {
2316           GetTextExtentPoint32W(hdc, buff, lstrlenW(buff), &sz);
2317           if (sz.cx > size.cx) size.cx = sz.cx;
2318       }
2319       else /* locale independent fallback on failure */
2320       {
2321           static const WCHAR SunW[] = { 'S','u','n',0 };
2322
2323           GetTextExtentPoint32W(hdc, SunW, lstrlenW(SunW), &size);
2324           break;
2325       }
2326   }
2327
2328   infoPtr->textWidth = size.cx + 2;
2329
2330   /* recalculate the height and width increments and offsets */
2331   GetTextExtentPoint32W(hdc, O0W, 2, &size);
2332
2333   xdiv = (infoPtr->dwStyle & MCS_WEEKNUMBERS) ? 8 : 7;
2334
2335   infoPtr->width_increment  = size.cx * 2 + 4;
2336   infoPtr->height_increment = infoPtr->textHeight;
2337
2338   /* calculate title area */
2339   title->top    = 0;
2340   title->bottom = 3 * infoPtr->height_increment / 2;
2341   title->left   = 0;
2342   title->right  = infoPtr->width_increment * xdiv;
2343
2344   /* set the dimensions of the next and previous buttons and center */
2345   /* the month text vertically */
2346   prev->top    = next->top    = title->top + 4;
2347   prev->bottom = next->bottom = title->bottom - 4;
2348   prev->left   = title->left + 4;
2349   prev->right  = prev->left + (title->bottom - title->top);
2350   next->right  = title->right - 4;
2351   next->left   = next->right - (title->bottom - title->top);
2352
2353   /* titlemonth->left and right change based upon the current month */
2354   /* and are recalculated in refresh as the current month may change */
2355   /* without the control being resized */
2356   titlemonth->top    = titleyear->top    = title->top    + (infoPtr->height_increment)/2;
2357   titlemonth->bottom = titleyear->bottom = title->bottom - (infoPtr->height_increment)/2;
2358
2359   /* setup the dimensions of the rectangle we draw the names of the */
2360   /* days of the week in */
2361   weeknumrect->left = 0;
2362
2363   if(infoPtr->dwStyle & MCS_WEEKNUMBERS)
2364     weeknumrect->right = prev->right;
2365   else
2366     weeknumrect->right = weeknumrect->left;
2367
2368   wdays->left   = days->left   = weeknumrect->right;
2369   wdays->right  = days->right  = wdays->left + 7 * infoPtr->width_increment;
2370   wdays->top    = title->bottom;
2371   wdays->bottom = wdays->top + infoPtr->height_increment;
2372
2373   days->top    = weeknumrect->top = wdays->bottom;
2374   days->bottom = weeknumrect->bottom = days->top + 6 * infoPtr->height_increment;
2375
2376   todayrect->left   = 0;
2377   todayrect->right  = title->right;
2378   todayrect->top    = days->bottom;
2379   todayrect->bottom = days->bottom + infoPtr->height_increment;
2380
2381   /* offset all rectangles to center in client area */
2382   dx = (rcClient.right  - title->right) / 2;
2383   dy = (rcClient.bottom - todayrect->bottom) / 2;
2384
2385   /* if calendar doesn't fit client area show it at left/top bounds */
2386   if (title->left + dx < 0) dx = 0;
2387   if (title->top  + dy < 0) dy = 0;
2388
2389   if (dx != 0 || dy != 0)
2390   {
2391     OffsetRect(title, dx, dy);
2392     OffsetRect(prev,  dx, dy);
2393     OffsetRect(next,  dx, dy);
2394     OffsetRect(titlemonth, dx, dy);
2395     OffsetRect(titleyear, dx, dy);
2396     OffsetRect(wdays, dx, dy);
2397     OffsetRect(weeknumrect, dx, dy);
2398     OffsetRect(days, dx, dy);
2399     OffsetRect(todayrect, dx, dy);
2400   }
2401
2402   TRACE("dx=%d dy=%d client[%s] title[%s] wdays[%s] days[%s] today[%s]\n",
2403         infoPtr->width_increment,infoPtr->height_increment,
2404         wine_dbgstr_rect(&rcClient),
2405         wine_dbgstr_rect(title),
2406         wine_dbgstr_rect(wdays),
2407         wine_dbgstr_rect(days),
2408         wine_dbgstr_rect(todayrect));
2409
2410   /* restore the originally selected font */
2411   SelectObject(hdc, currentFont);
2412
2413   ReleaseDC(infoPtr->hwndSelf, hdc);
2414 }
2415
2416 static LRESULT MONTHCAL_Size(MONTHCAL_INFO *infoPtr, int Width, int Height)
2417 {
2418   TRACE("(width=%d, height=%d)\n", Width, Height);
2419
2420   MONTHCAL_UpdateSize(infoPtr);
2421   InvalidateRect(infoPtr->hwndSelf, NULL, TRUE);
2422
2423   return 0;
2424 }
2425
2426 static LRESULT MONTHCAL_GetFont(const MONTHCAL_INFO *infoPtr)
2427 {
2428     return (LRESULT)infoPtr->hFont;
2429 }
2430
2431 static LRESULT MONTHCAL_SetFont(MONTHCAL_INFO *infoPtr, HFONT hFont, BOOL redraw)
2432 {
2433     HFONT hOldFont;
2434     LOGFONTW lf;
2435
2436     if (!hFont) return 0;
2437
2438     hOldFont = infoPtr->hFont;
2439     infoPtr->hFont = hFont;
2440
2441     GetObjectW(infoPtr->hFont, sizeof(lf), &lf);
2442     lf.lfWeight = FW_BOLD;
2443     infoPtr->hBoldFont = CreateFontIndirectW(&lf);
2444
2445     MONTHCAL_UpdateSize(infoPtr);
2446
2447     if (redraw)
2448         InvalidateRect(infoPtr->hwndSelf, NULL, FALSE);
2449
2450     return (LRESULT)hOldFont;
2451 }
2452
2453 /* update theme after a WM_THEMECHANGED message */
2454 static LRESULT theme_changed (const MONTHCAL_INFO* infoPtr)
2455 {
2456     HTHEME theme = GetWindowTheme (infoPtr->hwndSelf);
2457     CloseThemeData (theme);
2458     OpenThemeData (infoPtr->hwndSelf, themeClass);
2459     return 0;
2460 }
2461
2462 static INT MONTHCAL_StyleChanged(MONTHCAL_INFO *infoPtr, WPARAM wStyleType,
2463                                  const STYLESTRUCT *lpss)
2464 {
2465     TRACE("(styletype=%lx, styleOld=0x%08x, styleNew=0x%08x)\n",
2466           wStyleType, lpss->styleOld, lpss->styleNew);
2467
2468     if (wStyleType != GWL_STYLE) return 0;
2469
2470     infoPtr->dwStyle = lpss->styleNew;
2471
2472     /* make room for week numbers */
2473     if ((lpss->styleNew ^ lpss->styleOld) & MCS_WEEKNUMBERS)
2474         MONTHCAL_UpdateSize(infoPtr);
2475
2476     return 0;
2477 }
2478
2479 static INT MONTHCAL_StyleChanging(MONTHCAL_INFO *infoPtr, WPARAM wStyleType,
2480                                   STYLESTRUCT *lpss)
2481 {
2482     TRACE("(styletype=%lx, styleOld=0x%08x, styleNew=0x%08x)\n",
2483           wStyleType, lpss->styleOld, lpss->styleNew);
2484
2485     /* block MCS_MULTISELECT change */
2486     if ((lpss->styleNew ^ lpss->styleOld) & MCS_MULTISELECT)
2487     {
2488         if (lpss->styleOld & MCS_MULTISELECT)
2489             lpss->styleNew |= MCS_MULTISELECT;
2490         else
2491             lpss->styleNew &= ~MCS_MULTISELECT;
2492     }
2493
2494     return 0;
2495 }
2496
2497 /* FIXME: check whether dateMin/dateMax need to be adjusted. */
2498 static LRESULT
2499 MONTHCAL_Create(HWND hwnd, LPCREATESTRUCTW lpcs)
2500 {
2501   MONTHCAL_INFO *infoPtr;
2502
2503   /* allocate memory for info structure */
2504   infoPtr = Alloc(sizeof(MONTHCAL_INFO));
2505   SetWindowLongPtrW(hwnd, 0, (DWORD_PTR)infoPtr);
2506
2507   if (infoPtr == NULL) {
2508     ERR("could not allocate info memory!\n");
2509     return 0;
2510   }
2511
2512   infoPtr->hwndSelf = hwnd;
2513   infoPtr->hwndNotify = lpcs->hwndParent;
2514   infoPtr->dwStyle  = GetWindowLongW(hwnd, GWL_STYLE);
2515   infoPtr->calendars = Alloc(sizeof(CALENDAR_INFO));
2516   if (!infoPtr->calendars) goto fail;
2517
2518   infoPtr->cal_num = 1;
2519
2520   MONTHCAL_SetFont(infoPtr, GetStockObject(DEFAULT_GUI_FONT), FALSE);
2521
2522   /* initialize info structure */
2523   /* FIXME: calculate systemtime ->> localtime(substract timezoneinfo) */
2524
2525   GetLocalTime(&infoPtr->todaysDate);
2526   MONTHCAL_SetFirstDayOfWeek(infoPtr, -1);
2527
2528   infoPtr->maxSelCount   = (infoPtr->dwStyle & MCS_MULTISELECT) ? 7 : 1;
2529   infoPtr->monthRange    = 3;
2530
2531   infoPtr->monthdayState = Alloc(infoPtr->monthRange * sizeof(MONTHDAYSTATE));
2532   if (!infoPtr->monthdayState) goto fail;
2533
2534   infoPtr->colors[MCSC_BACKGROUND]   = comctl32_color.clrWindow;
2535   infoPtr->colors[MCSC_TEXT]         = comctl32_color.clrWindowText;
2536   infoPtr->colors[MCSC_TITLEBK]      = comctl32_color.clrActiveCaption;
2537   infoPtr->colors[MCSC_TITLETEXT]    = comctl32_color.clrWindow;
2538   infoPtr->colors[MCSC_MONTHBK]      = comctl32_color.clrWindow;
2539   infoPtr->colors[MCSC_TRAILINGTEXT] = comctl32_color.clrGrayText;
2540
2541   infoPtr->minSel = infoPtr->todaysDate;
2542   infoPtr->maxSel = infoPtr->todaysDate;
2543   infoPtr->calendars[0].month = infoPtr->todaysDate;
2544   infoPtr->isUnicode = TRUE;
2545
2546   /* call MONTHCAL_UpdateSize to set all of the dimensions */
2547   /* of the control */
2548   MONTHCAL_UpdateSize(infoPtr);
2549
2550   /* today auto update timer, to be freed only on control destruction */
2551   SetTimer(infoPtr->hwndSelf, MC_TODAYUPDATETIMER, MC_TODAYUPDATEDELAY, 0);
2552
2553   OpenThemeData (infoPtr->hwndSelf, themeClass);
2554
2555   return 0;
2556
2557 fail:
2558   Free(infoPtr->monthdayState);
2559   Free(infoPtr->calendars);
2560   Free(infoPtr);
2561   return 0;
2562 }
2563
2564 static LRESULT
2565 MONTHCAL_Destroy(MONTHCAL_INFO *infoPtr)
2566 {
2567   /* free month calendar info data */
2568   Free(infoPtr->monthdayState);
2569   Free(infoPtr->calendars);
2570   SetWindowLongPtrW(infoPtr->hwndSelf, 0, 0);
2571
2572   CloseThemeData (GetWindowTheme (infoPtr->hwndSelf));
2573   
2574   Free(infoPtr);
2575   return 0;
2576 }
2577
2578 /*
2579  * Handler for WM_NOTIFY messages
2580  */
2581 static LRESULT
2582 MONTHCAL_Notify(MONTHCAL_INFO *infoPtr, NMHDR *hdr)
2583 {
2584   /* notification from year edit updown */
2585   if (hdr->code == UDN_DELTAPOS)
2586   {
2587     NMUPDOWN *nmud = (NMUPDOWN*)hdr;
2588
2589     if (hdr->hwndFrom == infoPtr->hWndYearUpDown && nmud->iDelta)
2590     {
2591       /* year value limits are set up explicitly after updown creation */
2592       MONTHCAL_Scroll(infoPtr, 12 * nmud->iDelta);
2593       MONTHCAL_NotifyDayState(infoPtr);
2594       MONTHCAL_NotifySelectionChange(infoPtr);
2595     }
2596   }
2597   return 0;
2598 }
2599
2600 static inline BOOL
2601 MONTHCAL_SetUnicodeFormat(MONTHCAL_INFO *infoPtr, BOOL isUnicode)
2602 {
2603   BOOL prev = infoPtr->isUnicode;
2604   infoPtr->isUnicode = isUnicode;
2605   return prev;
2606 }
2607
2608 static inline BOOL
2609 MONTHCAL_GetUnicodeFormat(const MONTHCAL_INFO *infoPtr)
2610 {
2611   return infoPtr->isUnicode;
2612 }
2613
2614 static LRESULT WINAPI
2615 MONTHCAL_WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
2616 {
2617   MONTHCAL_INFO *infoPtr = (MONTHCAL_INFO *)GetWindowLongPtrW(hwnd, 0);
2618
2619   TRACE("hwnd=%p msg=%x wparam=%lx lparam=%lx\n", hwnd, uMsg, wParam, lParam);
2620
2621   if (!infoPtr && (uMsg != WM_CREATE))
2622     return DefWindowProcW(hwnd, uMsg, wParam, lParam);
2623   switch(uMsg)
2624   {
2625   case MCM_GETCURSEL:
2626     return MONTHCAL_GetCurSel(infoPtr, (LPSYSTEMTIME)lParam);
2627
2628   case MCM_SETCURSEL:
2629     return MONTHCAL_SetCurSel(infoPtr, (LPSYSTEMTIME)lParam);
2630
2631   case MCM_GETMAXSELCOUNT:
2632     return MONTHCAL_GetMaxSelCount(infoPtr);
2633
2634   case MCM_SETMAXSELCOUNT:
2635     return MONTHCAL_SetMaxSelCount(infoPtr, wParam);
2636
2637   case MCM_GETSELRANGE:
2638     return MONTHCAL_GetSelRange(infoPtr, (LPSYSTEMTIME)lParam);
2639
2640   case MCM_SETSELRANGE:
2641     return MONTHCAL_SetSelRange(infoPtr, (LPSYSTEMTIME)lParam);
2642
2643   case MCM_GETMONTHRANGE:
2644     return MONTHCAL_GetMonthRange(infoPtr, wParam, (SYSTEMTIME*)lParam);
2645
2646   case MCM_SETDAYSTATE:
2647     return MONTHCAL_SetDayState(infoPtr, (INT)wParam, (LPMONTHDAYSTATE)lParam);
2648
2649   case MCM_GETMINREQRECT:
2650     return MONTHCAL_GetMinReqRect(infoPtr, (LPRECT)lParam);
2651
2652   case MCM_GETCOLOR:
2653     return MONTHCAL_GetColor(infoPtr, wParam);
2654
2655   case MCM_SETCOLOR:
2656     return MONTHCAL_SetColor(infoPtr, wParam, (COLORREF)lParam);
2657
2658   case MCM_GETTODAY:
2659     return MONTHCAL_GetToday(infoPtr, (LPSYSTEMTIME)lParam);
2660
2661   case MCM_SETTODAY:
2662     return MONTHCAL_SetToday(infoPtr, (LPSYSTEMTIME)lParam);
2663
2664   case MCM_HITTEST:
2665     return MONTHCAL_HitTest(infoPtr, (PMCHITTESTINFO)lParam);
2666
2667   case MCM_GETFIRSTDAYOFWEEK:
2668     return MONTHCAL_GetFirstDayOfWeek(infoPtr);
2669
2670   case MCM_SETFIRSTDAYOFWEEK:
2671     return MONTHCAL_SetFirstDayOfWeek(infoPtr, (INT)lParam);
2672
2673   case MCM_GETRANGE:
2674     return MONTHCAL_GetRange(infoPtr, (LPSYSTEMTIME)lParam);
2675
2676   case MCM_SETRANGE:
2677     return MONTHCAL_SetRange(infoPtr, (SHORT)wParam, (LPSYSTEMTIME)lParam);
2678
2679   case MCM_GETMONTHDELTA:
2680     return MONTHCAL_GetMonthDelta(infoPtr);
2681
2682   case MCM_SETMONTHDELTA:
2683     return MONTHCAL_SetMonthDelta(infoPtr, wParam);
2684
2685   case MCM_GETMAXTODAYWIDTH:
2686     return MONTHCAL_GetMaxTodayWidth(infoPtr);
2687
2688   case MCM_SETUNICODEFORMAT:
2689     return MONTHCAL_SetUnicodeFormat(infoPtr, (BOOL)wParam);
2690
2691   case MCM_GETUNICODEFORMAT:
2692     return MONTHCAL_GetUnicodeFormat(infoPtr);
2693
2694   case WM_GETDLGCODE:
2695     return DLGC_WANTARROWS | DLGC_WANTCHARS;
2696
2697   case WM_RBUTTONUP:
2698     return MONTHCAL_RButtonUp(infoPtr, lParam);
2699
2700   case WM_LBUTTONDOWN:
2701     return MONTHCAL_LButtonDown(infoPtr, lParam);
2702
2703   case WM_MOUSEMOVE:
2704     return MONTHCAL_MouseMove(infoPtr, lParam);
2705
2706   case WM_LBUTTONUP:
2707     return MONTHCAL_LButtonUp(infoPtr, lParam);
2708
2709   case WM_PAINT:
2710     return MONTHCAL_Paint(infoPtr, (HDC)wParam);
2711
2712   case WM_PRINTCLIENT:
2713     return MONTHCAL_PrintClient(infoPtr, (HDC)wParam, (DWORD)lParam);
2714
2715   case WM_ERASEBKGND:
2716     return MONTHCAL_EraseBkgnd(infoPtr, (HDC)wParam);
2717
2718   case WM_SETFOCUS:
2719     return MONTHCAL_SetFocus(infoPtr);
2720
2721   case WM_SIZE:
2722     return MONTHCAL_Size(infoPtr, (SHORT)LOWORD(lParam), (SHORT)HIWORD(lParam));
2723
2724   case WM_NOTIFY:
2725     return MONTHCAL_Notify(infoPtr, (NMHDR*)lParam);
2726
2727   case WM_CREATE:
2728     return MONTHCAL_Create(hwnd, (LPCREATESTRUCTW)lParam);
2729
2730   case WM_SETFONT:
2731     return MONTHCAL_SetFont(infoPtr, (HFONT)wParam, (BOOL)lParam);
2732
2733   case WM_GETFONT:
2734     return MONTHCAL_GetFont(infoPtr);
2735
2736   case WM_TIMER:
2737     return MONTHCAL_Timer(infoPtr, wParam);
2738     
2739   case WM_THEMECHANGED:
2740     return theme_changed (infoPtr);
2741
2742   case WM_DESTROY:
2743     return MONTHCAL_Destroy(infoPtr);
2744
2745   case WM_SYSCOLORCHANGE:
2746     COMCTL32_RefreshSysColors();
2747     return 0;
2748
2749   case WM_STYLECHANGED:
2750     return MONTHCAL_StyleChanged(infoPtr, wParam, (LPSTYLESTRUCT)lParam);
2751
2752   case WM_STYLECHANGING:
2753     return MONTHCAL_StyleChanging(infoPtr, wParam, (LPSTYLESTRUCT)lParam);
2754
2755   default:
2756     if ((uMsg >= WM_USER) && (uMsg < WM_APP) && !COMCTL32_IsReflectedMessage(uMsg))
2757       ERR( "unknown msg %04x wp=%08lx lp=%08lx\n", uMsg, wParam, lParam);
2758     return DefWindowProcW(hwnd, uMsg, wParam, lParam);
2759   }
2760 }
2761
2762
2763 void
2764 MONTHCAL_Register(void)
2765 {
2766   WNDCLASSW wndClass;
2767
2768   ZeroMemory(&wndClass, sizeof(WNDCLASSW));
2769   wndClass.style         = CS_GLOBALCLASS;
2770   wndClass.lpfnWndProc   = MONTHCAL_WindowProc;
2771   wndClass.cbClsExtra    = 0;
2772   wndClass.cbWndExtra    = sizeof(MONTHCAL_INFO *);
2773   wndClass.hCursor       = LoadCursorW(0, (LPWSTR)IDC_ARROW);
2774   wndClass.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
2775   wndClass.lpszClassName = MONTHCAL_CLASSW;
2776
2777   RegisterClassW(&wndClass);
2778 }
2779
2780
2781 void
2782 MONTHCAL_Unregister(void)
2783 {
2784     UnregisterClassW(MONTHCAL_CLASSW, NULL);
2785 }