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