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