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