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