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