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