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