Avoid excessive heap memory reallocation when generating EMF
[wine] / dlls / comctl32 / updown.c
1 /*
2  * Updown control
3  *
4  * Copyright 1997, 2002 Dimitrie O. Paun
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  * NOTE
21  * 
22  * This code was audited for completeness against the documented features
23  * of Comctl32.dll version 6.0 on Sep. 9, 2002, by Dimitrie O. Paun.
24  * 
25  * Unless otherwise noted, we believe this code to be complete, as per
26  * the specification mentioned above.
27  * If you discover missing features, or bugs, please note them below.
28  * 
29  */
30
31 #include <stdlib.h>
32 #include <string.h>
33 #include <stdarg.h>
34 #include <stdio.h>
35
36 #include "windef.h"
37 #include "winbase.h"
38 #include "wingdi.h"
39 #include "winuser.h"
40 #include "winnls.h"
41 #include "commctrl.h"
42 #include "comctl32.h"
43 #include "wine/unicode.h"
44 #include "wine/debug.h"
45
46 WINE_DEFAULT_DEBUG_CHANNEL(updown);
47
48 typedef struct
49 {
50     HWND      Self;            /* Handle to this up-down control */
51     UINT      AccelCount;      /* Number of elements in AccelVect */
52     UDACCEL*  AccelVect;       /* Vector containing AccelCount elements */
53     INT       AccelIndex;      /* Current accel index, -1 if not accel'ing */
54     INT       Base;            /* Base to display nr in the buddy window */
55     INT       CurVal;          /* Current up-down value */
56     INT       MinVal;          /* Minimum up-down value */
57     INT       MaxVal;          /* Maximum up-down value */
58     HWND      Buddy;           /* Handle to the buddy window */
59     INT       BuddyType;       /* Remembers the buddy type BUDDY_TYPE_* */
60     INT       Flags;           /* Internal Flags FLAG_* */
61     BOOL      UnicodeFormat;   /* Marks the use of Unicode internally */
62 } UPDOWN_INFO;
63
64 /* Control configuration constants */
65
66 #define INITIAL_DELAY   500    /* initial timer until auto-inc kicks in */
67 #define AUTOPRESS_DELAY 250    /* time to keep arrow pressed on KEY_DOWN */
68 #define REPEAT_DELAY    50     /* delay between auto-increments */
69
70 #define DEFAULT_WIDTH       14 /* default width of the ctrl */
71 #define DEFAULT_XSEP         0 /* default separation between buddy and ctrl */
72 #define DEFAULT_ADDTOP       0 /* amount to extend above the buddy window */
73 #define DEFAULT_ADDBOT       0 /* amount to extend below the buddy window */
74 #define DEFAULT_BUDDYBORDER  2 /* Width/height of the buddy border */
75 #define DEFAULT_BUDDYSPACER  2 /* Spacer between the buddy and the ctrl */
76
77
78 /* Work constants */
79
80 #define FLAG_INCR       0x01
81 #define FLAG_DECR       0x02
82 #define FLAG_MOUSEIN    0x04
83 #define FLAG_PRESSED    0x08
84 #define FLAG_ARROW      (FLAG_INCR | FLAG_DECR)
85
86 #define BUDDY_TYPE_UNKNOWN 0
87 #define BUDDY_TYPE_LISTBOX 1
88 #define BUDDY_TYPE_EDIT    2
89
90 #define TIMER_AUTOREPEAT   1
91 #define TIMER_ACCEL        2
92 #define TIMER_AUTOPRESS    3
93
94 #define BUDDY_UPDOWN_HWND        "buddyUpDownHWND"
95 #define BUDDY_SUPERCLASS_WNDPROC "buddySupperClassWndProc"
96
97 #define UPDOWN_GetInfoPtr(hwnd) ((UPDOWN_INFO *)GetWindowLongA (hwnd,0))
98 #define COUNT_OF(a) (sizeof(a)/sizeof(a[0]))
99
100 static void UPDOWN_DoAction (UPDOWN_INFO *infoPtr, int delta, int action);
101
102 /***********************************************************************
103  *           UPDOWN_IsBuddyEdit
104  * Tests if our buddy is an edit control.
105  */
106 static inline BOOL UPDOWN_IsBuddyEdit(UPDOWN_INFO *infoPtr)
107 {
108     return infoPtr->BuddyType == BUDDY_TYPE_EDIT;
109 }
110
111 /***********************************************************************
112  *           UPDOWN_IsBuddyListbox
113  * Tests if our buddy is a listbox control.
114  */
115 static inline BOOL UPDOWN_IsBuddyListbox(UPDOWN_INFO *infoPtr)
116 {
117     return infoPtr->BuddyType == BUDDY_TYPE_LISTBOX;
118 }
119
120 /***********************************************************************
121  *           UPDOWN_InBounds
122  * Tests if a given value 'val' is between the Min&Max limits
123  */
124 static BOOL UPDOWN_InBounds(UPDOWN_INFO *infoPtr, int val)
125 {
126     if(infoPtr->MaxVal > infoPtr->MinVal)
127         return (infoPtr->MinVal <= val) && (val <= infoPtr->MaxVal);
128     else
129         return (infoPtr->MaxVal <= val) && (val <= infoPtr->MinVal);
130 }
131
132 /***********************************************************************
133  *           UPDOWN_OffsetVal
134  * Change the current value by delta.
135  * It returns TRUE is the value was changed successfuly, or FALSE
136  * if the value was not changed, as it would go out of bounds.
137  */
138 static BOOL UPDOWN_OffsetVal(UPDOWN_INFO *infoPtr, int delta)
139 {
140     /* check if we can do the modification first */
141     if(!UPDOWN_InBounds (infoPtr, infoPtr->CurVal+delta)) {
142         if (GetWindowLongW (infoPtr->Self, GWL_STYLE) & UDS_WRAP) {
143             delta += (delta < 0 ? -1 : 1) *
144                      (infoPtr->MaxVal < infoPtr->MinVal ? -1 : 1) *
145                      (infoPtr->MinVal - infoPtr->MaxVal) +
146                      (delta < 0 ? 1 : -1);
147         } else return FALSE;
148     }
149
150     infoPtr->CurVal += delta;
151     return TRUE;
152 }
153
154 /***********************************************************************
155  * UPDOWN_HasBuddyBorder
156  *
157  * When we have a buddy set and that we are aligned on our buddy, we
158  * want to draw a sunken edge to make like we are part of that control.
159  */
160 static BOOL UPDOWN_HasBuddyBorder(UPDOWN_INFO* infoPtr)
161 {
162     DWORD dwStyle = GetWindowLongW (infoPtr->Self, GWL_STYLE);
163
164     return  ( ((dwStyle & (UDS_ALIGNLEFT | UDS_ALIGNRIGHT)) != 0) &&
165               UPDOWN_IsBuddyEdit(infoPtr) );
166 }
167
168 /***********************************************************************
169  *           UPDOWN_GetArrowRect
170  * wndPtr   - pointer to the up-down wnd
171  * rect     - will hold the rectangle
172  * arrow    - FLAG_INCR to get the "increment" rect (up or right)
173  *            FLAG_DECR to get the "decrement" rect (down or left)
174  *            If both flags are pressent, the envelope is returned.
175  */
176 static void UPDOWN_GetArrowRect (UPDOWN_INFO* infoPtr, RECT *rect, int arrow)
177 {
178     DWORD dwStyle = GetWindowLongW (infoPtr->Self, GWL_STYLE);
179
180     GetClientRect (infoPtr->Self, rect);
181
182     /*
183      * Make sure we calculate the rectangle to fit even if we draw the
184      * border.
185      */
186     if (UPDOWN_HasBuddyBorder(infoPtr)) {
187         if (dwStyle & UDS_ALIGNLEFT)
188             rect->left += DEFAULT_BUDDYBORDER;
189         else
190             rect->right -= DEFAULT_BUDDYBORDER;
191
192         InflateRect(rect, 0, -DEFAULT_BUDDYBORDER);
193     }
194
195     /* now figure out if we need a space away from the buddy */
196     if ( IsWindow(infoPtr->Buddy) ) {
197         if (dwStyle & UDS_ALIGNLEFT) rect->right -= DEFAULT_BUDDYSPACER;
198         else rect->left += DEFAULT_BUDDYSPACER;
199     }
200
201     /*
202      * We're calculating the midpoint to figure-out where the
203      * separation between the buttons will lay. We make sure that we
204      * round the uneven numbers by adding 1.
205      */
206     if (dwStyle & UDS_HORZ) {
207         int len = rect->right - rect->left + 1; /* compute the width */
208         if (arrow & FLAG_INCR)
209             rect->left = rect->left + len/2;
210         if (arrow & FLAG_DECR)
211             rect->right =  rect->left + len/2 - 1;
212     } else {
213         int len = rect->bottom - rect->top + 1; /* compute the height */
214         if (arrow & FLAG_INCR)
215             rect->bottom =  rect->top + len/2 - 1;
216         if (arrow & FLAG_DECR)
217             rect->top =  rect->top + len/2;
218     }
219 }
220
221 /***********************************************************************
222  *           UPDOWN_GetArrowFromPoint
223  * Returns the rectagle (for the up or down arrow) that contains pt.
224  * If it returns the up rect, it returns TRUE.
225  * If it returns the down rect, it returns FALSE.
226  */
227 static BOOL UPDOWN_GetArrowFromPoint (UPDOWN_INFO* infoPtr, RECT *rect, POINT pt)
228 {
229     UPDOWN_GetArrowRect (infoPtr, rect, FLAG_INCR);
230     if(PtInRect(rect, pt)) return FLAG_INCR;
231
232     UPDOWN_GetArrowRect (infoPtr, rect, FLAG_DECR);
233     if(PtInRect(rect, pt)) return FLAG_DECR;
234
235     return 0;
236 }
237
238
239 /***********************************************************************
240  *           UPDOWN_GetThousandSep
241  * Returns the thousand sep. If an error occurs, it returns ','.
242  */
243 static WCHAR UPDOWN_GetThousandSep()
244 {
245     WCHAR sep[2];
246
247     if(GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_STHOUSAND, sep, 2) != 1)
248         sep[0] = ',';
249
250     return sep[0];
251 }
252
253 /***********************************************************************
254  *           UPDOWN_GetBuddyInt
255  * Tries to read the pos from the buddy window and if it succeeds,
256  * it stores it in the control's CurVal
257  * returns:
258  *   TRUE  - if it read the integer from the buddy successfully
259  *   FALSE - if an error occurred
260  */
261 static BOOL UPDOWN_GetBuddyInt (UPDOWN_INFO *infoPtr)
262 {
263     WCHAR txt[20], sep, *src, *dst;
264     int newVal;
265
266     if (!IsWindow(infoPtr->Buddy))
267         return FALSE;
268
269     /*if the buddy is a list window, we must set curr index */
270     if (UPDOWN_IsBuddyListbox(infoPtr)) {
271         newVal = SendMessageW(infoPtr->Buddy, LB_GETCARETINDEX, 0, 0);
272         if(newVal < 0) return FALSE;
273     } else {
274         /* we have a regular window, so will get the text */
275         if (!GetWindowTextW(infoPtr->Buddy, txt, COUNT_OF(txt))) return FALSE;
276
277         sep = UPDOWN_GetThousandSep();
278
279         /* now get rid of the separators */
280         for(src = dst = txt; *src; src++)
281             if(*src != sep) *dst++ = *src;
282         *dst = 0;
283
284         /* try to convert the number and validate it */
285         newVal = strtolW(txt, &src, infoPtr->Base);
286         if(*src || !UPDOWN_InBounds (infoPtr, newVal)) return FALSE;
287     }
288
289     TRACE("new value(%d) from buddy (old=%d)\n", newVal, infoPtr->CurVal);
290     infoPtr->CurVal = newVal;
291     return TRUE;
292 }
293
294
295 /***********************************************************************
296  *           UPDOWN_SetBuddyInt
297  * Tries to set the pos to the buddy window based on current pos
298  * returns:
299  *   TRUE  - if it set the caption of the  buddy successfully
300  *   FALSE - if an error occurred
301  */
302 static BOOL UPDOWN_SetBuddyInt (UPDOWN_INFO *infoPtr)
303 {
304     WCHAR fmt[3] = { '%', 'd', '\0' };
305     WCHAR txt[20];
306     int len;
307
308     if (!IsWindow(infoPtr->Buddy)) return FALSE;
309
310     TRACE("set new value(%d) to buddy.\n", infoPtr->CurVal);
311
312     /*if the buddy is a list window, we must set curr index */
313     if (UPDOWN_IsBuddyListbox(infoPtr)) {
314         return SendMessageW(infoPtr->Buddy, LB_SETCURSEL, infoPtr->CurVal, 0) != LB_ERR;
315     }
316
317     /* Regular window, so set caption to the number */
318     if (infoPtr->Base == 16) fmt[1] = 'X';
319     len = wsprintfW(txt, fmt, infoPtr->CurVal);
320
321
322     /* Do thousands separation if necessary */
323     if (!(GetWindowLongW (infoPtr->Self, GWL_STYLE) & UDS_NOTHOUSANDS) && (len > 3)) {
324         WCHAR tmp[COUNT_OF(txt)], *src = tmp, *dst = txt;
325         WCHAR sep = UPDOWN_GetThousandSep();
326         int start = len % 3;
327
328         memcpy(tmp, txt, sizeof(txt));
329         if (start == 0) start = 3;
330         dst += start;
331         src += start;
332         for (len=0; *src; len++) {
333             if (len % 3 == 0) *dst++ = sep;
334             *dst++ = *src++;
335         }
336         *dst = 0;
337     }
338
339     return SetWindowTextW(infoPtr->Buddy, txt);
340 }
341
342 /***********************************************************************
343  * UPDOWN_Draw
344  *
345  * Draw the arrows. The background need not be erased.
346  */
347 static LRESULT UPDOWN_Draw (UPDOWN_INFO *infoPtr, HDC hdc)
348 {
349     DWORD dwStyle = GetWindowLongW (infoPtr->Self, GWL_STYLE);
350     BOOL pressed, hot;
351     RECT rect;
352
353     /* Draw the common border between ourselves and our buddy */
354     if (UPDOWN_HasBuddyBorder(infoPtr)) {
355         GetClientRect(infoPtr->Self, &rect);
356         DrawEdge(hdc, &rect, EDGE_SUNKEN,
357                  BF_BOTTOM | BF_TOP |
358                  (dwStyle & UDS_ALIGNLEFT ? BF_LEFT : BF_RIGHT));
359     }
360
361     /* Draw the incr button */
362     UPDOWN_GetArrowRect (infoPtr, &rect, FLAG_INCR);
363     pressed = (infoPtr->Flags & FLAG_PRESSED) && (infoPtr->Flags & FLAG_INCR);
364     hot = (infoPtr->Flags & FLAG_INCR) && (infoPtr->Flags & FLAG_MOUSEIN);
365     DrawFrameControl(hdc, &rect, DFC_SCROLL,
366         (dwStyle & UDS_HORZ ? DFCS_SCROLLRIGHT : DFCS_SCROLLUP) |
367         ((dwStyle & UDS_HOTTRACK) && hot ? DFCS_HOT : 0) |
368         (pressed ? DFCS_PUSHED : 0) |
369         (dwStyle & WS_DISABLED ? DFCS_INACTIVE : 0) );
370
371     /* Draw the decr button */
372     UPDOWN_GetArrowRect(infoPtr, &rect, FLAG_DECR);
373     pressed = (infoPtr->Flags & FLAG_PRESSED) && (infoPtr->Flags & FLAG_DECR);
374     hot = (infoPtr->Flags & FLAG_DECR) && (infoPtr->Flags & FLAG_MOUSEIN);
375     DrawFrameControl(hdc, &rect, DFC_SCROLL,
376         (dwStyle & UDS_HORZ ? DFCS_SCROLLLEFT : DFCS_SCROLLDOWN) |
377         ((dwStyle & UDS_HOTTRACK) && hot ? DFCS_HOT : 0) |
378         (pressed ? DFCS_PUSHED : 0) |
379         (dwStyle & WS_DISABLED ? DFCS_INACTIVE : 0) );
380
381     return 0;
382 }
383
384 /***********************************************************************
385  * UPDOWN_Paint
386  *
387  * Asynchronous drawing (must ONLY be used in WM_PAINT).
388  * Calls UPDOWN_Draw.
389  */
390 static LRESULT UPDOWN_Paint (UPDOWN_INFO *infoPtr, HDC hdc)
391 {
392     PAINTSTRUCT ps;
393     if (hdc) return UPDOWN_Draw (infoPtr, hdc);
394     hdc = BeginPaint (infoPtr->Self, &ps);
395     UPDOWN_Draw (infoPtr, hdc);
396     EndPaint (infoPtr->Self, &ps);
397     return 0;
398 }
399
400 /***********************************************************************
401  * UPDOWN_KeyPressed
402  *
403  * Handle key presses (up & down) when we have to do so
404  */
405 static LRESULT UPDOWN_KeyPressed(UPDOWN_INFO *infoPtr, int key)
406 {
407     int arrow;
408
409     if (key == VK_UP) arrow = FLAG_INCR;
410     else if (key == VK_DOWN) arrow = FLAG_DECR;
411     else return 1;
412
413     UPDOWN_GetBuddyInt (infoPtr);
414     infoPtr->Flags &= ~FLAG_ARROW;
415     infoPtr->Flags |= FLAG_PRESSED | arrow;
416     InvalidateRect (infoPtr->Self, NULL, FALSE);
417     SetTimer(infoPtr->Self, TIMER_AUTOPRESS, AUTOPRESS_DELAY, 0);
418     UPDOWN_DoAction (infoPtr, 1, arrow);
419     return 0;
420 }
421
422 /***********************************************************************
423  * UPDOWN_Buddy_SubclassProc used to handle messages sent to the buddy
424  *                           control.
425  */
426 static LRESULT CALLBACK
427 UPDOWN_Buddy_SubclassProc(HWND  hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
428 {
429     WNDPROC superClassWndProc = (WNDPROC)GetPropA(hwnd, BUDDY_SUPERCLASS_WNDPROC);
430     TRACE("hwnd=%p, wndProc=%d, uMsg=%04x, wParam=%d, lParam=%d\n",
431           hwnd, (INT)superClassWndProc, uMsg, wParam, (UINT)lParam);
432
433     if (uMsg == WM_KEYDOWN) {
434         HWND upDownHwnd = GetPropA(hwnd, BUDDY_UPDOWN_HWND);
435
436         UPDOWN_KeyPressed(UPDOWN_GetInfoPtr(upDownHwnd), (int)wParam);
437     }
438
439     return CallWindowProcW( superClassWndProc, hwnd, uMsg, wParam, lParam);
440 }
441
442 /***********************************************************************
443  *           UPDOWN_SetBuddy
444  * Tests if 'bud' is a valid window handle. If not, returns FALSE.
445  * Else, sets it as a new Buddy.
446  * Then, it should subclass the buddy
447  * If window has the UDS_ARROWKEYS, it subcalsses the buddy window to
448  * process the UP/DOWN arrow keys.
449  * If window has the UDS_ALIGNLEFT or UDS_ALIGNRIGHT style
450  * the size/pos of the buddy and the control are adjusted accordingly.
451  */
452 static BOOL UPDOWN_SetBuddy (UPDOWN_INFO* infoPtr, HWND bud)
453 {
454     DWORD dwStyle = GetWindowLongW (infoPtr->Self, GWL_STYLE);
455     RECT  budRect;  /* new coord for the buddy */
456     int   x, width;  /* new x position and width for the up-down */
457     WNDPROC baseWndProc;
458     CHAR buddyClass[40];
459
460     /* Is it a valid bud? */
461     if(!IsWindow(bud)) return FALSE;
462
463     TRACE("(hwnd=%p, bud=%p)\n", infoPtr->Self, bud);
464
465     /* there is already a body assigned */
466     if (infoPtr->Buddy)  RemovePropA(infoPtr->Buddy, BUDDY_UPDOWN_HWND);
467
468     /* Store buddy window handle */
469     infoPtr->Buddy = bud;
470
471     /* keep upDown ctrl hwnd in a buddy property */
472     SetPropA( bud, BUDDY_UPDOWN_HWND, infoPtr->Self);
473
474     /* Store buddy window class type */
475     infoPtr->BuddyType = BUDDY_TYPE_UNKNOWN;
476     if (GetClassNameA(bud, buddyClass, COUNT_OF(buddyClass))) {
477         if (lstrcmpiA(buddyClass, "Edit") == 0)
478             infoPtr->BuddyType = BUDDY_TYPE_EDIT;
479         else if (lstrcmpiA(buddyClass, "Listbox") == 0)
480             infoPtr->BuddyType = BUDDY_TYPE_LISTBOX;
481     }
482
483     if(dwStyle & UDS_ARROWKEYS){
484         /* Note that I don't clear the BUDDY_SUPERCLASS_WNDPROC property
485            when we reset the upDown ctrl buddy to another buddy because it is not
486            good to break the window proc chain. */
487         if (!GetPropA(bud, BUDDY_SUPERCLASS_WNDPROC)) {
488             baseWndProc = (WNDPROC)SetWindowLongW(bud, GWL_WNDPROC, (LPARAM)UPDOWN_Buddy_SubclassProc);
489             SetPropA(bud, BUDDY_SUPERCLASS_WNDPROC, (HANDLE)baseWndProc);
490         }
491     }
492
493     /* Get the rect of the buddy relative to its parent */
494     GetWindowRect(infoPtr->Buddy, &budRect);
495     MapWindowPoints(HWND_DESKTOP, GetParent(infoPtr->Buddy), (POINT *)(&budRect.left), 2);
496
497     /* now do the positioning */
498     if  (dwStyle & UDS_ALIGNLEFT) {
499         x  = budRect.left;
500         budRect.left += DEFAULT_WIDTH + DEFAULT_XSEP;
501     } else if (dwStyle & UDS_ALIGNRIGHT) {
502         budRect.right -= DEFAULT_WIDTH + DEFAULT_XSEP;
503         x  = budRect.right+DEFAULT_XSEP;
504     } else {
505         x  = budRect.right+DEFAULT_XSEP;
506     }
507
508     /* first adjust the buddy to accomodate the up/down */
509     SetWindowPos(infoPtr->Buddy, 0, budRect.left, budRect.top,
510                  budRect.right  - budRect.left, budRect.bottom - budRect.top,
511                  SWP_NOACTIVATE|SWP_NOZORDER);
512
513     /* now position the up/down */
514     /* Since the UDS_ALIGN* flags were used, */
515     /* we will pick the position and size of the window. */
516     width = DEFAULT_WIDTH;
517
518     /*
519      * If the updown has a buddy border, it has to overlap with the buddy
520      * to look as if it is integrated with the buddy control.
521      * We nudge the control or change it size to overlap.
522      */
523     if (UPDOWN_HasBuddyBorder(infoPtr)) {
524         if(dwStyle & UDS_ALIGNLEFT)
525             width += DEFAULT_BUDDYBORDER;
526         else
527             x -= DEFAULT_BUDDYBORDER;
528     }
529
530     SetWindowPos(infoPtr->Self, infoPtr->Buddy, x,
531                  budRect.top - DEFAULT_ADDTOP, width,
532                  budRect.bottom - budRect.top + DEFAULT_ADDTOP + DEFAULT_ADDBOT,
533                  SWP_NOACTIVATE);
534
535     return TRUE;
536 }
537
538 /***********************************************************************
539  *           UPDOWN_DoAction
540  *
541  * This function increments/decrements the CurVal by the
542  * 'delta' amount according to the 'action' flag which can be a
543  * combination of FLAG_INCR and FLAG_DECR
544  * It notifies the parent as required.
545  * It handles wraping and non-wraping correctly.
546  * It is assumed that delta>0
547  */
548 static void UPDOWN_DoAction (UPDOWN_INFO *infoPtr, int delta, int action)
549 {
550     DWORD dwStyle = GetWindowLongW (infoPtr->Self, GWL_STYLE);
551     NM_UPDOWN ni;
552
553     TRACE("%d by %d\n", action, delta);
554
555     /* check if we can do the modification first */
556     delta *= (action & FLAG_INCR ? 1 : -1) * (infoPtr->MaxVal < infoPtr->MinVal ? -1 : 1);
557     if ( (action & FLAG_INCR) && (action & FLAG_DECR) ) delta = 0;
558
559     /* We must notify parent now to obtain permission */
560     ni.iPos = infoPtr->CurVal;
561     ni.iDelta = delta;
562     ni.hdr.hwndFrom = infoPtr->Self;
563     ni.hdr.idFrom   = GetWindowLongW (infoPtr->Self, GWL_ID);
564     ni.hdr.code = UDN_DELTAPOS;
565     if (!SendMessageW(GetParent (infoPtr->Self), WM_NOTIFY,
566                    (WPARAM)ni.hdr.idFrom, (LPARAM)&ni)) {
567         /* Parent said: OK to adjust */
568
569         /* Now adjust value with (maybe new) delta */
570         if (UPDOWN_OffsetVal (infoPtr, ni.iDelta)) {
571             /* Now take care about our buddy */
572             if (dwStyle & UDS_SETBUDDYINT) UPDOWN_SetBuddyInt (infoPtr);
573         }
574     }
575
576     /* Also, notify it. This message is sent in any case. */
577     SendMessageW( GetParent(infoPtr->Self),
578                   dwStyle & UDS_HORZ ? WM_HSCROLL : WM_VSCROLL,
579                   MAKELONG(SB_THUMBPOSITION, infoPtr->CurVal),
580                   (LPARAM)infoPtr->Self);
581 }
582
583 /***********************************************************************
584  *           UPDOWN_IsEnabled
585  *
586  * Returns TRUE if it is enabled as well as its buddy (if any)
587  *         FALSE otherwise
588  */
589 static BOOL UPDOWN_IsEnabled (UPDOWN_INFO *infoPtr)
590 {
591     if(GetWindowLongW (infoPtr->Self, GWL_STYLE) & WS_DISABLED)
592         return FALSE;
593     if(infoPtr->Buddy)
594         return IsWindowEnabled(infoPtr->Buddy);
595     return TRUE;
596 }
597
598 /***********************************************************************
599  *           UPDOWN_CancelMode
600  *
601  * Deletes any timers, releases the mouse and does  redraw if necessary.
602  * If the control is not in "capture" mode, it does nothing.
603  * If the control was not in cancel mode, it returns FALSE.
604  * If the control was in cancel mode, it returns TRUE.
605  */
606 static BOOL UPDOWN_CancelMode (UPDOWN_INFO *infoPtr)
607 {
608     if (!(infoPtr->Flags & FLAG_PRESSED)) return FALSE;
609
610     KillTimer (infoPtr->Self, TIMER_AUTOREPEAT);
611     KillTimer (infoPtr->Self, TIMER_ACCEL);
612     KillTimer (infoPtr->Self, TIMER_AUTOPRESS);
613
614     if (GetCapture() == infoPtr->Self) {
615         NMHDR hdr;
616         hdr.hwndFrom = infoPtr->Self;
617         hdr.idFrom   = GetWindowLongW (infoPtr->Self, GWL_ID);
618         hdr.code = NM_RELEASEDCAPTURE;
619         SendMessageW(GetParent (infoPtr->Self), WM_NOTIFY, hdr.idFrom, (LPARAM)&hdr);
620         ReleaseCapture();
621     }
622
623     infoPtr->Flags &= ~FLAG_PRESSED;
624     InvalidateRect (infoPtr->Self, NULL, FALSE);
625
626     return TRUE;
627 }
628
629 /***********************************************************************
630  *           UPDOWN_HandleMouseEvent
631  *
632  * Handle a mouse event for the updown.
633  * 'pt' is the location of the mouse event in client or
634  * windows coordinates.
635  */
636 static void UPDOWN_HandleMouseEvent (UPDOWN_INFO *infoPtr, UINT msg, POINTS pts)
637 {
638     DWORD dwStyle = GetWindowLongW (infoPtr->Self, GWL_STYLE);
639     POINT pt = { pts.x, pts.y };
640     RECT rect;
641     int temp, arrow;
642
643     switch(msg)
644     {
645         case WM_LBUTTONDOWN:  /* Initialise mouse tracking */
646             /* If we are inside an arrow, then nothing to do */
647             if(!(infoPtr->Flags & FLAG_MOUSEIN)) return;
648
649             /* If the buddy is an edit, will set focus to it */
650             if (UPDOWN_IsBuddyEdit(infoPtr)) SetFocus(infoPtr->Buddy);
651
652             /* Now see which one is the 'active' arrow */
653             if (infoPtr->Flags & FLAG_ARROW) {
654
655                 /* Update the CurVal if necessary */
656                 if (dwStyle & UDS_SETBUDDYINT) UPDOWN_GetBuddyInt (infoPtr);
657
658                 /* Set up the correct flags */
659                 infoPtr->Flags |= FLAG_PRESSED;
660
661                 /* repaint the control */
662                 InvalidateRect (infoPtr->Self, NULL, FALSE);
663
664                 /* process the click */
665                 UPDOWN_DoAction (infoPtr, 1, infoPtr->Flags & FLAG_ARROW);
666
667                 /* now capture all mouse messages */
668                 SetCapture (infoPtr->Self);
669
670                 /* and startup the first timer */
671                 SetTimer(infoPtr->Self, TIMER_AUTOREPEAT, INITIAL_DELAY, 0);
672             }
673             break;
674
675         case WM_MOUSEMOVE:
676             /* save the flags to see if any got modified */
677             temp = infoPtr->Flags;
678
679             /* Now see which one is the 'active' arrow */
680             arrow = UPDOWN_GetArrowFromPoint (infoPtr, &rect, pt);
681
682             /* Update the flags if we are in/out */
683             infoPtr->Flags &= ~(FLAG_MOUSEIN | FLAG_ARROW);
684             if(arrow) {
685                 infoPtr->Flags |=  FLAG_MOUSEIN | arrow;
686             } else {
687                 if(infoPtr->AccelIndex != -1) infoPtr->AccelIndex = 0;
688             }
689
690             /* If state changed, redraw the control */
691             if(temp != infoPtr->Flags)
692                  InvalidateRect (infoPtr->Self, &rect, FALSE);
693             break;
694
695         default:
696             ERR("Impossible case (msg=%x)!\n", msg);
697     }
698
699 }
700
701 /***********************************************************************
702  *           UpDownWndProc
703  */
704 static LRESULT WINAPI UpDownWindowProc(HWND hwnd, UINT message, WPARAM wParam,
705                                 LPARAM lParam)
706 {
707     UPDOWN_INFO *infoPtr = UPDOWN_GetInfoPtr (hwnd);
708     DWORD dwStyle = GetWindowLongW (hwnd, GWL_STYLE);
709     int temp;
710
711     if (!infoPtr && (message != WM_CREATE))
712         return DefWindowProcW (hwnd, message, wParam, lParam);
713
714     switch(message)
715     {
716         case WM_CREATE:
717             SetWindowLongW (hwnd, GWL_STYLE, dwStyle & ~WS_BORDER);
718             infoPtr = (UPDOWN_INFO*)Alloc (sizeof(UPDOWN_INFO));
719             SetWindowLongW (hwnd, 0, (DWORD)infoPtr);
720
721             /* initialize the info struct */
722             infoPtr->Self = hwnd;
723             infoPtr->AccelCount = 0;
724             infoPtr->AccelVect = 0;
725             infoPtr->AccelIndex = -1;
726             infoPtr->CurVal = 0;
727             infoPtr->MinVal = 100;
728             infoPtr->MaxVal = 0;
729             infoPtr->Base  = 10; /* Default to base 10  */
730             infoPtr->Buddy = 0;  /* No buddy window yet */
731             infoPtr->Flags = 0;  /* And no flags        */
732
733             /* Do we pick the buddy win ourselves? */
734             if (dwStyle & UDS_AUTOBUDDY)
735                 UPDOWN_SetBuddy (infoPtr, GetWindow (hwnd, GW_HWNDPREV));
736
737             TRACE("UpDown Ctrl creation, hwnd=%p\n", hwnd);
738             break;
739
740         case WM_DESTROY:
741             if(infoPtr->AccelVect) Free (infoPtr->AccelVect);
742
743             if(infoPtr->Buddy) RemovePropA(infoPtr->Buddy, BUDDY_UPDOWN_HWND);
744
745             Free (infoPtr);
746             SetWindowLongW (hwnd, 0, 0);
747             TRACE("UpDown Ctrl destruction, hwnd=%p\n", hwnd);
748             break;
749
750         case WM_ENABLE:
751             if (dwStyle & WS_DISABLED) UPDOWN_CancelMode (infoPtr);
752             InvalidateRect (infoPtr->Self, NULL, FALSE);
753             break;
754
755         case WM_TIMER:
756            /* is this the auto-press timer? */
757            if(wParam == TIMER_AUTOPRESS) {
758                 KillTimer(hwnd, TIMER_AUTOPRESS);
759                 infoPtr->Flags &= ~(FLAG_PRESSED | FLAG_ARROW);
760                 InvalidateRect(infoPtr->Self, NULL, FALSE);
761            }
762
763            /* if initial timer, kill it and start the repeat timer */
764            if(wParam == TIMER_AUTOREPEAT) {
765                 KillTimer(hwnd, TIMER_AUTOREPEAT);
766                 /* if no accel info given, used default timer */
767                 if(infoPtr->AccelCount==0 || infoPtr->AccelVect==0) {
768                     infoPtr->AccelIndex = -1;
769                     temp = REPEAT_DELAY;
770                 } else {
771                     infoPtr->AccelIndex = 0; /* otherwise, use it */
772                     temp = infoPtr->AccelVect[infoPtr->AccelIndex].nSec * 1000 + 1;
773                 }
774                 SetTimer(hwnd, TIMER_ACCEL, temp, 0);
775             }
776
777             /* now, if the mouse is above us, do the thing...*/
778             if(infoPtr->Flags & FLAG_MOUSEIN) {
779                 temp = infoPtr->AccelIndex == -1 ? 1 : infoPtr->AccelVect[infoPtr->AccelIndex].nInc;
780                 UPDOWN_DoAction(infoPtr, temp, infoPtr->Flags & FLAG_ARROW);
781
782                 if(infoPtr->AccelIndex != -1 && infoPtr->AccelIndex < infoPtr->AccelCount-1) {
783                     KillTimer(hwnd, TIMER_ACCEL);
784                     infoPtr->AccelIndex++; /* move to the next accel info */
785                     temp = infoPtr->AccelVect[infoPtr->AccelIndex].nSec * 1000 + 1;
786                     /* make sure we have at least 1ms intervals */
787                     SetTimer(hwnd, TIMER_ACCEL, temp, 0);
788                 }
789             }
790             break;
791
792         case WM_CANCELMODE:
793           return UPDOWN_CancelMode (infoPtr);
794
795         case WM_LBUTTONUP:
796             if (GetCapture() != infoPtr->Self) break;
797
798             if ( (infoPtr->Flags & FLAG_MOUSEIN) &&
799                  (infoPtr->Flags & FLAG_ARROW) ) {
800
801                 SendMessageW( GetParent(hwnd),
802                               dwStyle & UDS_HORZ ? WM_HSCROLL : WM_VSCROLL,
803                               MAKELONG(SB_ENDSCROLL, infoPtr->CurVal),
804                               (LPARAM)hwnd);
805                 if (UPDOWN_IsBuddyEdit(infoPtr))
806                     SendMessageW(infoPtr->Buddy, EM_SETSEL, 0, MAKELONG(0, -1));
807             }
808             UPDOWN_CancelMode(infoPtr);
809             break;
810
811         case WM_LBUTTONDOWN:
812         case WM_MOUSEMOVE:
813             if(UPDOWN_IsEnabled(infoPtr))
814                 UPDOWN_HandleMouseEvent (infoPtr, message, MAKEPOINTS(lParam));
815             break;
816
817         case WM_KEYDOWN:
818             if((dwStyle & UDS_ARROWKEYS) && UPDOWN_IsEnabled(infoPtr))
819                 return UPDOWN_KeyPressed(infoPtr, (int)wParam);
820             break;
821
822         case WM_PAINT:
823             return UPDOWN_Paint (infoPtr, (HDC)wParam);
824
825         case UDM_GETACCEL:
826             if (wParam==0 && lParam==0) return infoPtr->AccelCount;
827             if (wParam && lParam) {
828                 temp = min(infoPtr->AccelCount, wParam);
829                 memcpy((void *)lParam, infoPtr->AccelVect, temp*sizeof(UDACCEL));
830                 return temp;
831             }
832             return 0;
833
834         case UDM_SETACCEL:
835             TRACE("UpDown Ctrl new accel info, hwnd=%p\n", hwnd);
836             if(infoPtr->AccelVect) {
837                 Free (infoPtr->AccelVect);
838                 infoPtr->AccelCount = 0;
839                 infoPtr->AccelVect  = 0;
840             }
841             if(wParam==0) return TRUE;
842             infoPtr->AccelVect = Alloc (wParam*sizeof(UDACCEL));
843             if(infoPtr->AccelVect == 0) return FALSE;
844             memcpy(infoPtr->AccelVect, (void*)lParam, wParam*sizeof(UDACCEL));
845             return TRUE;
846
847         case UDM_GETBASE:
848             return infoPtr->Base;
849
850         case UDM_SETBASE:
851             TRACE("UpDown Ctrl new base(%d), hwnd=%p\n", wParam, hwnd);
852             if (wParam==10 || wParam==16) {
853                 temp = infoPtr->Base;
854                 infoPtr->Base = wParam;
855                 return temp;
856             }
857             break;
858
859         case UDM_GETBUDDY:
860             return (LRESULT)infoPtr->Buddy;
861
862         case UDM_SETBUDDY:
863             temp = (int)infoPtr->Buddy;
864             UPDOWN_SetBuddy (infoPtr, (HWND)wParam);
865             return temp;
866
867         case UDM_GETPOS:
868             temp = UPDOWN_GetBuddyInt (infoPtr);
869             return MAKELONG(infoPtr->CurVal, temp ? 0 : 1);
870
871         case UDM_SETPOS:
872             temp = (short)LOWORD(lParam);
873             TRACE("UpDown Ctrl new value(%d), hwnd=%p\n", temp, hwnd);
874             if(!UPDOWN_InBounds(infoPtr, temp)) {
875                 if(temp < infoPtr->MinVal) temp = infoPtr->MinVal;
876                 if(temp > infoPtr->MaxVal) temp = infoPtr->MaxVal;
877             }
878             wParam = infoPtr->CurVal;
879             infoPtr->CurVal = temp;
880             if(dwStyle & UDS_SETBUDDYINT) UPDOWN_SetBuddyInt (infoPtr);
881             return wParam;            /* return prev value */
882
883         case UDM_GETRANGE:
884             return MAKELONG(infoPtr->MaxVal, infoPtr->MinVal);
885
886         case UDM_SETRANGE:
887                                                      /* we must have:     */
888             infoPtr->MaxVal = (short)(lParam);       /* UD_MINVAL <= Max <= UD_MAXVAL */
889             infoPtr->MinVal = (short)HIWORD(lParam); /* UD_MINVAL <= Min <= UD_MAXVAL */
890                                                      /* |Max-Min| <= UD_MAXVAL        */
891             TRACE("UpDown Ctrl new range(%d to %d), hwnd=%p\n",
892                   infoPtr->MinVal, infoPtr->MaxVal, hwnd);
893             break;
894
895         case UDM_GETRANGE32:
896             if (wParam) *(LPINT)wParam = infoPtr->MinVal;
897             if (lParam) *(LPINT)lParam = infoPtr->MaxVal;
898             break;
899
900         case UDM_SETRANGE32:
901             infoPtr->MinVal = (INT)wParam;
902             infoPtr->MaxVal = (INT)lParam;
903             if (infoPtr->MaxVal <= infoPtr->MinVal)
904                 infoPtr->MaxVal = infoPtr->MinVal + 1;
905             TRACE("UpDown Ctrl new range(%d to %d), hwnd=%p\n",
906                   infoPtr->MinVal, infoPtr->MaxVal, hwnd);
907             break;
908
909         case UDM_GETPOS32:
910             if ((LPBOOL)lParam != NULL) *((LPBOOL)lParam) = TRUE;
911             return infoPtr->CurVal;
912
913         case UDM_SETPOS32:
914             if(!UPDOWN_InBounds(infoPtr, (int)lParam)) {
915                 if((int)lParam < infoPtr->MinVal) lParam = infoPtr->MinVal;
916                 if((int)lParam > infoPtr->MaxVal) lParam = infoPtr->MaxVal;
917             }
918             temp = infoPtr->CurVal;         /* save prev value   */
919             infoPtr->CurVal = (int)lParam;  /* set the new value */
920             if(dwStyle & UDS_SETBUDDYINT) UPDOWN_SetBuddyInt (infoPtr);
921             return temp;                    /* return prev value */
922
923         case UDM_GETUNICODEFORMAT:
924             /* we lie a bit here, we're always using Unicode internally */
925             return infoPtr->UnicodeFormat;
926
927         case UDM_SETUNICODEFORMAT:
928             /* do we really need to honour this flag? */
929             temp = infoPtr->UnicodeFormat;
930             infoPtr->UnicodeFormat = (BOOL)wParam;
931             return temp;
932
933         default:
934             if ((message >= WM_USER) && (message < WM_APP))
935                 ERR("unknown msg %04x wp=%04x lp=%08lx\n", message, wParam, lParam);
936             return DefWindowProcW (hwnd, message, wParam, lParam);
937     }
938
939     return 0;
940 }
941
942 /***********************************************************************
943  *              UPDOWN_Register [Internal]
944  *
945  * Registers the updown window class.
946  */
947 void UPDOWN_Register(void)
948 {
949     WNDCLASSW wndClass;
950
951     ZeroMemory( &wndClass, sizeof( WNDCLASSW ) );
952     wndClass.style         = CS_GLOBALCLASS | CS_VREDRAW;
953     wndClass.lpfnWndProc   = (WNDPROC)UpDownWindowProc;
954     wndClass.cbClsExtra    = 0;
955     wndClass.cbWndExtra    = sizeof(UPDOWN_INFO*);
956     wndClass.hCursor       = LoadCursorW( 0, (LPWSTR)IDC_ARROW );
957     wndClass.hbrBackground = (HBRUSH)(COLOR_3DFACE + 1);
958     wndClass.lpszClassName = UPDOWN_CLASSW;
959
960     RegisterClassW( &wndClass );
961 }
962
963
964 /***********************************************************************
965  *              UPDOWN_Unregister       [Internal]
966  *
967  * Unregisters the updown window class.
968  */
969 void UPDOWN_Unregister (void)
970 {
971     UnregisterClassW (UPDOWN_CLASSW, NULL);
972 }