Fixed test so 0xffffffff is properly recognized.
[wine] / dlls / comctl32 / treeview.c
1 /* Treeview control
2  *
3  * Copyright 1998 Eric Kohl <ekohl@abo.rhein-zeitung.de>
4  * Copyright 1998,1999 Alex Priem <alexp@sci.kun.nl>
5  * Copyright 1999 Sylvain St-Germain
6  *
7  * Note that TREEVIEW_INFO * and HTREEITEM are the same thing.
8  *
9  * Note2: All items always! have valid (allocated) pszText field.
10  *      If item's text == LPSTR_TEXTCALLBACKA we allocate buffer
11  *      of size TEXT_CALLBACK_SIZE in DoSetItem.
12  *      We use callbackMask to keep track of fields to be updated.
13  *
14  * TODO:
15  *   missing notifications: NM_SETCURSOR, TVN_GETINFOTIP, TVN_KEYDOWN,
16  *      TVN_SETDISPINFO, TVN_SINGLEEXPAND
17  *
18  *   missing styles: TVS_FULLROWSELECT, TVS_INFOTIP, TVS_NOSCROLL,
19  *      TVS_RTLREADING, TVS_TRACKSELECT
20  *
21  *   missing item styles: TVIS_CUT, TVIS_EXPANDPARTIAL
22  *
23  *   Make the insertion mark look right.
24  *   Scroll (instead of repaint) as much as possible.
25  */
26
27 #include <assert.h>
28 #include <ctype.h>
29 #include <string.h>
30 #include <limits.h>
31 #include <stdlib.h>
32
33 #include "winbase.h"
34 #include "wingdi.h"
35 #include "commctrl.h"
36 #include "comctl32.h"
37 #include "debugtools.h"
38
39 /* internal structures */
40
41 typedef struct _TREEITEM    /* HTREEITEM is a _TREEINFO *. */
42 {
43   UINT      callbackMask;
44   UINT      state;
45   UINT      stateMask;
46   LPSTR     pszText;
47   int       cchTextMax;
48   int       iImage;
49   int       iSelectedImage;
50   int       cChildren;
51   LPARAM    lParam;
52   int       iIntegral;      /* item height multiplier (1 is normal) */
53   int       iLevel;         /* indentation level:0=root level */
54   HTREEITEM parent;         /* handle to parent or 0 if at root*/
55   HTREEITEM firstChild;     /* handle to first child or 0 if no child*/
56   HTREEITEM lastChild;
57   HTREEITEM prevSibling;    /* handle to prev item in list, 0 if first */
58   HTREEITEM nextSibling;    /* handle to next item in list, 0 if last */
59   RECT      rect;
60   LONG      linesOffset;
61   LONG      stateOffset;
62   LONG      imageOffset;
63   LONG      textOffset;
64   LONG      textWidth;      /* horizontal text extent for pszText */
65   LONG      visibleOrder;   /* visible ordering, 0 is first visible item */
66 } TREEVIEW_ITEM;
67
68
69 typedef struct tagTREEVIEW_INFO
70 {
71   HWND          hwnd;
72   HWND          hwndNotify;     /* Owner window to send notifications to */
73   DWORD         dwStyle;
74   HTREEITEM     root;
75   UINT          uInternalStatus;
76   INT           Timer;
77   UINT          uNumItems;      /* number of valid TREEVIEW_ITEMs */
78   INT           cdmode;         /* last custom draw setting */
79   UINT          uScrollTime;    /* max. time for scrolling in milliseconds */
80   BOOL          bRedraw;        /* if FALSE we validate but don't redraw in TREEVIEW_Paint() */
81
82   UINT          uItemHeight;    /* item height */
83   BOOL          bHeightSet;
84
85   LONG          clientWidth;    /* width of control window */
86   LONG          clientHeight;   /* height of control window */
87
88   LONG          treeWidth;      /* width of visible tree items */
89   LONG          treeHeight;     /* height of visible tree items */
90
91   UINT          uIndent;        /* indentation in pixels */
92   HTREEITEM     selectedItem;   /* handle to selected item or 0 if none */
93   HTREEITEM     hotItem;        /* handle currently under cursor, 0 if none */
94   HTREEITEM     focusedItem;    /* item that was under the cursor when WM_LBUTTONDOWN was received */
95
96   HTREEITEM     firstVisible;   /* handle to first visible item */
97   LONG          maxVisibleOrder;
98   HTREEITEM     dropItem;       /* handle to item selected by drag cursor */
99   HTREEITEM     insertMarkItem; /* item after which insertion mark is placed */
100   BOOL          insertBeforeorAfter; /* flag used by TVM_SETINSERTMARK */
101   HIMAGELIST    dragList;       /* Bitmap of dragged item */
102   LONG          scrollX;
103   COLORREF      clrBk;
104   COLORREF      clrText;
105   COLORREF      clrLine;
106   COLORREF      clrInsertMark;
107   HFONT         hFont;
108   HFONT         hBoldFont;
109   HWND          hwndToolTip;
110
111   HWND          hwndEdit;
112   WNDPROC       wpEditOrig;     /* orig window proc for subclassing edit */
113   BOOL          bIgnoreEditKillFocus;
114   BOOL          bLabelChanged;
115
116   HIMAGELIST    himlNormal;
117   int           normalImageHeight;
118   int           normalImageWidth;
119   HIMAGELIST    himlState;
120   int           stateImageHeight;
121   int           stateImageWidth;
122   HDPA          items;
123
124   DWORD lastKeyPressTimestamp; /* Added */
125   WPARAM charCode; /* Added */
126   INT nSearchParamLength; /* Added */
127   CHAR szSearchParam[ MAX_PATH ]; /* Added */
128 } TREEVIEW_INFO;
129
130
131 /******** Defines that TREEVIEW_ProcessLetterKeys uses ****************/
132 #define KEY_DELAY       450
133
134 /* bitflags for infoPtr->uInternalStatus */
135
136 #define TV_HSCROLL      0x01    /* treeview too large to fit in window */
137 #define TV_VSCROLL      0x02    /* (horizontal/vertical) */
138 #define TV_LDRAG                0x04    /* Lbutton pushed to start drag */
139 #define TV_LDRAGGING    0x08    /* Lbutton pushed, mouse moved.  */
140 #define TV_RDRAG                0x10    /* dito Rbutton */
141 #define TV_RDRAGGING    0x20    
142
143 /* bitflags for infoPtr->timer */
144
145 #define TV_EDIT_TIMER    2
146 #define TV_EDIT_TIMER_SET 2
147
148
149 VOID TREEVIEW_Register (VOID);
150 VOID TREEVIEW_Unregister (VOID);
151
152
153 DEFAULT_DEBUG_CHANNEL(treeview);
154
155
156 #define TEXT_CALLBACK_SIZE 260
157
158 #define TREEVIEW_LEFT_MARGIN 8
159
160 #define MINIMUM_INDENT 19
161
162 #define CALLBACK_MASK_ALL (TVIF_TEXT|TVIF_CHILDREN|TVIF_IMAGE|TVIF_SELECTEDIMAGE)
163
164 #define STATEIMAGEINDEX(x) (((x) >> 12) & 0x0f)
165 #define OVERLAYIMAGEINDEX(x) (((x) >> 8) & 0x0f)
166 #define ISVISIBLE(x)         ((x)->visibleOrder >= 0)
167
168
169 typedef VOID (*TREEVIEW_ItemEnumFunc)(TREEVIEW_INFO *, TREEVIEW_ITEM *,LPVOID);
170
171
172 static VOID TREEVIEW_Invalidate(TREEVIEW_INFO *, TREEVIEW_ITEM *);
173
174 static LRESULT TREEVIEW_DoSelectItem(TREEVIEW_INFO *, INT, HTREEITEM, INT);
175 static VOID TREEVIEW_SetFirstVisible(TREEVIEW_INFO *, TREEVIEW_ITEM *, BOOL);
176 static LRESULT TREEVIEW_EnsureVisible(TREEVIEW_INFO *, HTREEITEM, BOOL);
177 static LRESULT TREEVIEW_RButtonUp(TREEVIEW_INFO *, LPPOINT);
178 static LRESULT TREEVIEW_EndEditLabelNow(TREEVIEW_INFO *infoPtr, BOOL bCancel);
179 static VOID TREEVIEW_UpdateScrollBars(TREEVIEW_INFO *infoPtr);
180 static LRESULT TREEVIEW_HScroll(TREEVIEW_INFO *, WPARAM);
181
182
183 /* Random Utilities *****************************************************/
184
185 #ifndef NDEBUG
186 static inline void
187 TREEVIEW_VerifyTree(TREEVIEW_INFO *infoPtr)
188 {
189     (void)infoPtr;
190 }
191 #else
192 /* The definition is at the end of the file. */
193 static void TREEVIEW_VerifyTree(TREEVIEW_INFO *infoPtr);
194 #endif
195
196 /* Returns the treeview private data if hwnd is a treeview.
197  * Otherwise returns an undefined value. */
198 static TREEVIEW_INFO *
199 TREEVIEW_GetInfoPtr(HWND hwnd)
200 {
201     return (TREEVIEW_INFO *)GetWindowLongA(hwnd, 0);
202 }
203
204 /* Don't call this. Nothing wants an item index. */
205 static inline int
206 TREEVIEW_GetItemIndex(TREEVIEW_INFO *infoPtr, HTREEITEM handle)
207 {
208     assert(infoPtr != NULL);
209
210     return DPA_GetPtrIndex(infoPtr->items, handle);
211 }
212
213 /***************************************************************************
214  * This method checks that handle is an item for this tree.
215  */
216 static BOOL
217 TREEVIEW_ValidItem(TREEVIEW_INFO *infoPtr, HTREEITEM handle)
218 {
219     if (TREEVIEW_GetItemIndex(infoPtr, handle) == -1)
220     {
221         TRACE("invalid item %p\n", handle);
222         return FALSE;
223     }
224     else
225         return TRUE;
226 }
227
228 static HFONT
229 TREEVIEW_CreateBoldFont(HFONT hOrigFont)
230 {
231     LOGFONTA font;
232
233     GetObjectA(hOrigFont, sizeof(font), &font);
234     font.lfWeight = FW_BOLD;
235     return CreateFontIndirectA(&font);
236 }
237
238 static inline HFONT
239 TREEVIEW_FontForItem(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *item)
240 {
241     return (item->state & TVIS_BOLD) ? infoPtr->hBoldFont : infoPtr->hFont;
242 }
243
244 /* for trace/debugging purposes only */
245 static const char *
246 TREEVIEW_ItemName(TREEVIEW_ITEM *item)
247 {
248     if (item == NULL) return "<null item>";
249     if (item->pszText == LPSTR_TEXTCALLBACKA) return "<callback>";
250     if (item->pszText == NULL) return "<null>";
251     return item->pszText;
252 }
253
254 /* An item is not a child of itself. */
255 static BOOL
256 TREEVIEW_IsChildOf(TREEVIEW_ITEM *parent, TREEVIEW_ITEM *child)
257 {
258     do
259     {
260         child = child->parent;
261         if (child == parent) return TRUE;
262     } while (child != NULL);
263
264     return FALSE;
265 }
266
267
268 /* Tree Traversal *******************************************************/
269
270 /***************************************************************************
271  * This method returns the last expanded sibling or child child item
272  * of a tree node
273  */
274 static TREEVIEW_ITEM *
275 TREEVIEW_GetLastListItem(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *wineItem)
276 {
277     if (!wineItem)
278        return NULL;
279
280     while (wineItem->lastChild)
281     {
282        if (wineItem->state & TVIS_EXPANDED)
283           wineItem = wineItem->lastChild;
284        else
285           break;
286     }
287
288     if (wineItem == infoPtr->root)
289         return NULL;
290
291     return wineItem;
292 }
293
294 /***************************************************************************
295  * This method returns the previous non-hidden item in the list not 
296  * considering the tree hierarchy.
297  */
298 static TREEVIEW_ITEM *
299 TREEVIEW_GetPrevListItem(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *tvItem)
300 {
301     if (tvItem->prevSibling)
302     {
303         /* This item has a prevSibling, get the last item in the sibling's tree. */
304         TREEVIEW_ITEM *upItem = tvItem->prevSibling;
305
306         if ((upItem->state & TVIS_EXPANDED) && upItem->lastChild != NULL)
307             return TREEVIEW_GetLastListItem(infoPtr, upItem->lastChild);
308         else
309             return upItem;
310     }
311     else
312     {
313         /* this item does not have a prevSibling, get the parent */
314         return (tvItem->parent != infoPtr->root) ? tvItem->parent : NULL;
315     }
316 }
317
318
319 /***************************************************************************
320  * This method returns the next physical item in the treeview not 
321  * considering the tree hierarchy.
322  */
323 static TREEVIEW_ITEM *
324 TREEVIEW_GetNextListItem(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *tvItem)
325 {
326     assert(tvItem != NULL);
327
328     /* 
329      * If this item has children and is expanded, return the first child
330      */
331     if ((tvItem->state & TVIS_EXPANDED) && tvItem->firstChild != NULL)
332     {
333         return tvItem->firstChild;
334     }
335
336
337     /*
338      * try to get the sibling
339      */
340     if (tvItem->nextSibling)
341         return tvItem->nextSibling;
342
343     /*
344      * Otherwise, get the parent's sibling.
345      */
346     while (tvItem->parent)
347     {
348         tvItem = tvItem->parent;
349
350         if (tvItem->nextSibling)
351             return tvItem->nextSibling;
352     }
353
354     return NULL;
355 }
356
357 /***************************************************************************
358  * This method returns the nth item starting at the given item.  It returns 
359  * the last item (or first) we we run out of items.
360  *
361  * Will scroll backward if count is <0.
362  *             forward if count is >0.
363  */
364 static TREEVIEW_ITEM *
365 TREEVIEW_GetListItem(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *wineItem,
366                      LONG count)
367 {
368     TREEVIEW_ITEM *(*next_item)(TREEVIEW_INFO *, TREEVIEW_ITEM *);
369     TREEVIEW_ITEM *previousItem;
370
371     assert(wineItem != NULL);
372
373     if (count > 0)
374     {
375         next_item = TREEVIEW_GetNextListItem;
376     }
377     else if (count < 0)
378     {
379         count = -count;
380         next_item = TREEVIEW_GetPrevListItem;
381     }
382     else
383         return wineItem;
384
385     do
386     {
387         previousItem = wineItem;
388         wineItem = next_item(infoPtr, wineItem);
389
390     } while (--count && wineItem != NULL);
391
392
393     return wineItem ? wineItem : previousItem;
394 }
395
396 /* Notifications ************************************************************/
397
398 static BOOL
399 TREEVIEW_SendSimpleNotify(TREEVIEW_INFO *infoPtr, UINT code)
400 {
401     NMHDR nmhdr;
402     HWND hwnd = infoPtr->hwnd;
403
404     TRACE("%x\n", code);
405     nmhdr.hwndFrom = hwnd;
406     nmhdr.idFrom = GetWindowLongA(hwnd, GWL_ID);
407     nmhdr.code = code;
408
409     return (BOOL)SendMessageA(infoPtr->hwndNotify, WM_NOTIFY,
410                               (WPARAM)nmhdr.idFrom, (LPARAM)&nmhdr);
411 }
412
413 static VOID
414 TREEVIEW_TVItemFromItem(UINT mask, TVITEMA *tvItem, TREEVIEW_ITEM *item)
415 {
416     tvItem->mask = mask;
417     tvItem->hItem = item;
418     tvItem->state = item->state;
419     tvItem->stateMask = 0;
420     tvItem->iImage = item->iImage;
421     tvItem->pszText = item->pszText;
422     tvItem->cchTextMax = item->cchTextMax;
423     tvItem->iImage = item->iImage;
424     tvItem->iSelectedImage = item->iSelectedImage;
425     tvItem->cChildren = item->cChildren;
426     tvItem->lParam = item->lParam;
427 }
428
429 static BOOL
430 TREEVIEW_SendTreeviewNotify(TREEVIEW_INFO *infoPtr, UINT code, UINT action,
431                             UINT mask, HTREEITEM oldItem, HTREEITEM newItem)
432 {
433     HWND hwnd = infoPtr->hwnd;
434     NMTREEVIEWA nmhdr;
435
436     TRACE("code:%x action:%x olditem:%p newitem:%p\n",
437           code, action, oldItem, newItem);
438
439     ZeroMemory(&nmhdr, sizeof(NMTREEVIEWA));
440
441     nmhdr.hdr.hwndFrom = hwnd;
442     nmhdr.hdr.idFrom = GetWindowLongA(hwnd, GWL_ID);
443     nmhdr.hdr.code = code;
444     nmhdr.action = action;
445
446     if (oldItem)
447         TREEVIEW_TVItemFromItem(mask, &nmhdr.itemOld, oldItem);
448
449     if (newItem)
450         TREEVIEW_TVItemFromItem(mask, &nmhdr.itemNew, newItem);
451
452     nmhdr.ptDrag.x = 0;
453     nmhdr.ptDrag.y = 0;
454
455     return (BOOL)SendMessageA(infoPtr->hwndNotify, WM_NOTIFY,
456                               (WPARAM)GetWindowLongA(hwnd, GWL_ID),
457                               (LPARAM)&nmhdr);
458 }
459
460 static BOOL
461 TREEVIEW_SendTreeviewDnDNotify(TREEVIEW_INFO *infoPtr, UINT code,
462                                HTREEITEM dragItem, POINT pt)
463 {
464     HWND hwnd = infoPtr->hwnd;
465     NMTREEVIEWA nmhdr;
466
467     TRACE("code:%x dragitem:%p\n", code, dragItem);
468
469     nmhdr.hdr.hwndFrom = hwnd;
470     nmhdr.hdr.idFrom = GetWindowLongA(hwnd, GWL_ID);
471     nmhdr.hdr.code = code;
472     nmhdr.action = 0;
473     nmhdr.itemNew.mask = TVIF_STATE | TVIF_PARAM | TVIF_HANDLE;
474     nmhdr.itemNew.hItem = dragItem;
475     nmhdr.itemNew.state = dragItem->state;
476     nmhdr.itemNew.lParam = dragItem->lParam;
477
478     nmhdr.ptDrag.x = pt.x;
479     nmhdr.ptDrag.y = pt.y;
480
481     return (BOOL)SendMessageA(infoPtr->hwndNotify, WM_NOTIFY,
482                               (WPARAM)GetWindowLongA(hwnd, GWL_ID),
483                               (LPARAM)&nmhdr);
484 }
485
486
487 static BOOL
488 TREEVIEW_SendCustomDrawNotify(TREEVIEW_INFO *infoPtr, DWORD dwDrawStage,
489                               HDC hdc, RECT rc)
490 {
491     HWND hwnd = infoPtr->hwnd;
492     NMTVCUSTOMDRAW nmcdhdr;
493     LPNMCUSTOMDRAW nmcd;
494
495     TRACE("drawstage:%lx hdc:%x\n", dwDrawStage, hdc);
496
497     nmcd = &nmcdhdr.nmcd;
498     nmcd->hdr.hwndFrom = hwnd;
499     nmcd->hdr.idFrom = GetWindowLongA(hwnd, GWL_ID);
500     nmcd->hdr.code = NM_CUSTOMDRAW;
501     nmcd->dwDrawStage = dwDrawStage;
502     nmcd->hdc = hdc;
503     nmcd->rc = rc;
504     nmcd->dwItemSpec = 0;
505     nmcd->uItemState = 0;
506     nmcd->lItemlParam = 0;
507     nmcdhdr.clrText = infoPtr->clrText;
508     nmcdhdr.clrTextBk = infoPtr->clrBk;
509     nmcdhdr.iLevel = 0;
510
511     return (BOOL)SendMessageA(infoPtr->hwndNotify, WM_NOTIFY,
512                               (WPARAM)GetWindowLongA(hwnd, GWL_ID),
513                               (LPARAM)&nmcdhdr);
514 }
515
516
517
518 /* FIXME: need to find out when the flags in uItemState need to be set */
519
520 static BOOL
521 TREEVIEW_SendCustomDrawItemNotify(TREEVIEW_INFO *infoPtr, HDC hdc,
522                                   TREEVIEW_ITEM *wineItem, UINT uItemDrawState)
523 {
524     HWND hwnd = infoPtr->hwnd;
525     NMTVCUSTOMDRAW nmcdhdr;
526     LPNMCUSTOMDRAW nmcd;
527     DWORD dwDrawStage, dwItemSpec;
528     UINT uItemState;
529     INT retval;
530
531     dwDrawStage = CDDS_ITEM | uItemDrawState;
532     dwItemSpec = (DWORD)wineItem;
533     uItemState = 0;
534     if (wineItem->state & TVIS_SELECTED)
535         uItemState |= CDIS_SELECTED;
536     if (wineItem == infoPtr->selectedItem)
537         uItemState |= CDIS_FOCUS;
538     if (wineItem == infoPtr->hotItem)
539         uItemState |= CDIS_HOT;
540
541     nmcd = &nmcdhdr.nmcd;
542     nmcd->hdr.hwndFrom = hwnd;
543     nmcd->hdr.idFrom = GetWindowLongA(hwnd, GWL_ID);
544     nmcd->hdr.code = NM_CUSTOMDRAW;
545     nmcd->dwDrawStage = dwDrawStage;
546     nmcd->hdc = hdc;
547     nmcd->rc = wineItem->rect;
548     nmcd->dwItemSpec = dwItemSpec;
549     nmcd->uItemState = uItemState;
550     nmcd->lItemlParam = wineItem->lParam;
551     nmcdhdr.clrText = infoPtr->clrText;
552     nmcdhdr.clrTextBk = infoPtr->clrBk;
553     nmcdhdr.iLevel = wineItem->iLevel;
554
555     TRACE("drawstage:%lx hdc:%x item:%lx, itemstate:%x, lItemlParam:%lx\n",
556           nmcd->dwDrawStage, nmcd->hdc, nmcd->dwItemSpec,
557           nmcd->uItemState, nmcd->lItemlParam);
558
559     retval = SendMessageA(infoPtr->hwndNotify, WM_NOTIFY,
560                           (WPARAM)GetWindowLongA(hwnd, GWL_ID),
561                           (LPARAM)&nmcdhdr);
562
563     infoPtr->clrText = nmcdhdr.clrText;
564     infoPtr->clrBk = nmcdhdr.clrTextBk;
565     return (BOOL)retval;
566 }
567
568 static BOOL
569 TREEVIEW_BeginLabelEditNotify(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *editItem)
570 {
571     HWND hwnd = infoPtr->hwnd;
572     NMTVDISPINFOA tvdi;
573
574     tvdi.hdr.hwndFrom = hwnd;
575     tvdi.hdr.idFrom = GetWindowLongA(hwnd, GWL_ID);
576     tvdi.hdr.code = TVN_BEGINLABELEDITA;
577
578     tvdi.item.mask = TVIF_HANDLE | TVIF_STATE | TVIF_PARAM | TVIF_TEXT;
579     tvdi.item.hItem = editItem;
580     tvdi.item.state = editItem->state;
581     tvdi.item.lParam = editItem->lParam;
582     tvdi.item.pszText = editItem->pszText;
583     tvdi.item.cchTextMax = editItem->cchTextMax;
584
585     return SendMessageA(infoPtr->hwndNotify, WM_NOTIFY, tvdi.hdr.idFrom,
586                         (LPARAM)&tvdi);
587 }
588
589 static void
590 TREEVIEW_UpdateDispInfo(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *wineItem,
591                         UINT mask)
592 {
593     NMTVDISPINFOA callback;
594     HWND hwnd = infoPtr->hwnd;
595
596     mask &= wineItem->callbackMask;
597
598     if (mask == 0) return;
599
600     callback.hdr.hwndFrom         = hwnd;
601     callback.hdr.idFrom           = GetWindowLongA(hwnd, GWL_ID);
602     callback.hdr.code             = TVN_GETDISPINFOA;
603
604     /* 'state' always contains valid value, as well as 'lParam'.
605      * All other parameters are uninitialized.
606      */
607     callback.item.pszText         = wineItem->pszText;
608     callback.item.cchTextMax      = wineItem->cchTextMax;
609     callback.item.mask            = mask;
610     callback.item.hItem           = wineItem;
611     callback.item.state           = wineItem->state;
612     callback.item.lParam          = wineItem->lParam;
613
614     /* If text is changed we need to recalculate textWidth */
615     if (mask & TVIF_TEXT)
616        wineItem->textWidth = 0;
617
618     SendMessageA(infoPtr->hwndNotify, WM_NOTIFY, callback.hdr.idFrom, (LPARAM)&callback);
619
620     /* It may have changed due to a call to SetItem. */ 
621     mask &= wineItem->callbackMask;
622
623     if ((mask & TVIF_TEXT) && callback.item.pszText != wineItem->pszText)
624     {
625         /* Instead of copying text into our buffer user specified its own */
626         int len = max(lstrlenA(callback.item.pszText) + 1, TEXT_CALLBACK_SIZE);
627         LPSTR newText = COMCTL32_ReAlloc(wineItem->pszText, len);
628
629         if (newText)
630         {
631            wineItem->pszText = newText;
632            strcpy(wineItem->pszText, callback.item.pszText);
633            wineItem->cchTextMax = len;
634         }
635         /* If ReAlloc fails we have nothing to do, but keep original text */
636     }
637
638     if (mask & TVIF_IMAGE)
639         wineItem->iImage = callback.item.iImage;
640
641     if (mask & TVIF_SELECTEDIMAGE)
642         wineItem->iSelectedImage = callback.item.iSelectedImage;
643
644     if (mask & TVIF_CHILDREN)
645         wineItem->cChildren = callback.item.cChildren;
646
647     /* These members are now permanently set. */
648     if (callback.item.mask & TVIF_DI_SETITEM)
649         wineItem->callbackMask &= ~callback.item.mask;
650 }
651
652 /***************************************************************************
653  * This function uses cChildren field to decide whether the item has
654  * children or not.
655  * Note: if this returns TRUE, the child items may not actually exist,
656  * they could be virtual.
657  *
658  * Just use wineItem->firstChild to check for physical children.
659  */
660 static BOOL
661 TREEVIEW_HasChildren(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *wineItem)
662 {
663     TREEVIEW_UpdateDispInfo(infoPtr, wineItem, TVIF_CHILDREN);
664
665     return wineItem->cChildren > 0;
666 }
667
668
669 /* Item Position ********************************************************/
670
671 /* Compute linesOffset, stateOffset, imageOffset, textOffset of an item. */
672 static VOID
673 TREEVIEW_ComputeItemInternalMetrics(TREEVIEW_INFO *infoPtr,
674                                     TREEVIEW_ITEM *item)
675 {
676     /* Same effect, different optimisation. */
677 #if 0
678     BOOL lar = ((infoPtr->dwStyle & TVS_LINESATROOT)
679                 && (infoPtr->dwStyle & (TVS_HASLINES|TVS_HASBUTTONS)));
680 #else
681     BOOL lar = ((infoPtr->dwStyle
682                  & (TVS_LINESATROOT|TVS_HASLINES|TVS_HASBUTTONS))
683                 > TVS_LINESATROOT);
684 #endif
685
686     item->linesOffset = infoPtr->uIndent * (item->iLevel + lar - 1)
687         - infoPtr->scrollX;
688     item->stateOffset = item->linesOffset + infoPtr->uIndent;
689     item->imageOffset = item->stateOffset
690         + (STATEIMAGEINDEX(item->state) ? infoPtr->stateImageWidth : 0);
691     item->textOffset  = item->imageOffset + infoPtr->normalImageWidth;
692 }
693
694 static VOID
695 TREEVIEW_ComputeTextWidth(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *item, HDC hDC)
696 {
697     HDC hdc;
698     HFONT hOldFont=0;
699     SIZE sz;
700
701     /* DRAW's OM docker creates items like this */
702     if (item->pszText == NULL)
703     {
704         item->textWidth = 0;
705         return;
706     }
707
708     if (item->textWidth != 0 && !(item->callbackMask & TVIF_TEXT))
709        return;
710
711     if (hDC != 0)
712     {
713         hdc = hDC;
714     }
715     else
716     {
717         hdc = GetDC(infoPtr->hwnd);
718         hOldFont = SelectObject(hdc, TREEVIEW_FontForItem(infoPtr, item));
719     }
720
721     GetTextExtentPoint32A(hdc, item->pszText, strlen(item->pszText), &sz);
722     item->textWidth = sz.cx;
723
724     if (hDC == 0)
725     {
726         SelectObject(hdc, hOldFont);
727         ReleaseDC(0, hdc);
728     }
729 }
730
731 static VOID
732 TREEVIEW_ComputeItemRect(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *item)
733 {
734     item->rect.top = infoPtr->uItemHeight *
735         (item->visibleOrder - infoPtr->firstVisible->visibleOrder);
736
737     item->rect.bottom = item->rect.top
738         + infoPtr->uItemHeight * item->iIntegral - 1;
739
740     item->rect.left = 0;
741     item->rect.right = infoPtr->clientWidth;
742 }
743
744 /* We know that only items after start need their order updated. */
745 static void
746 TREEVIEW_RecalculateVisibleOrder(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *start)
747 {
748     TREEVIEW_ITEM *item;
749     int order;
750
751     if (!start)
752     {
753         start = infoPtr->root->firstChild;
754         order = 0;
755     }
756     else
757         order = start->visibleOrder;
758
759     for (item = start; item != NULL;
760          item = TREEVIEW_GetNextListItem(infoPtr, item))
761     {
762         item->visibleOrder = order;
763         order += item->iIntegral;
764     }
765
766     infoPtr->maxVisibleOrder = order;
767
768     for (item = start; item != NULL;
769          item = TREEVIEW_GetNextListItem(infoPtr, item))
770     {
771         TREEVIEW_ComputeItemRect(infoPtr, item);
772     }
773 }
774
775
776 /* Update metrics of all items in selected subtree.
777  * root must be expanded
778  */
779 static VOID
780 TREEVIEW_UpdateSubTree(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *root)
781 {
782    TREEVIEW_ITEM *sibling;
783    HDC hdc;
784    HFONT hOldFont;
785
786    if (!root->firstChild || !(root->state & TVIS_EXPANDED))
787       return;
788
789    root->state &= ~TVIS_EXPANDED;
790    sibling = TREEVIEW_GetNextListItem(infoPtr, root);
791    root->state |= TVIS_EXPANDED;
792
793    hdc = GetDC(infoPtr->hwnd);
794    hOldFont = SelectObject(hdc, infoPtr->hFont);
795
796    for (; root != sibling;
797         root = TREEVIEW_GetNextListItem(infoPtr, root))
798    {
799       TREEVIEW_ComputeItemInternalMetrics(infoPtr, root);
800
801       if (root->callbackMask & TVIF_TEXT)
802          TREEVIEW_UpdateDispInfo(infoPtr, root, TVIF_TEXT);
803
804       if (root->textWidth == 0)
805       {
806          SelectObject(hdc, TREEVIEW_FontForItem(infoPtr, root));
807          TREEVIEW_ComputeTextWidth(infoPtr, root, hdc);
808       }
809    }
810
811    SelectObject(hdc, hOldFont);
812    ReleaseDC(infoPtr->hwnd, hdc);
813 }
814
815 /* Item Allocation **********************************************************/
816
817 static TREEVIEW_ITEM *
818 TREEVIEW_AllocateItem(TREEVIEW_INFO *infoPtr)
819 {
820     TREEVIEW_ITEM *newItem = COMCTL32_Alloc(sizeof(TREEVIEW_ITEM));
821
822     if (!newItem)
823         return NULL;
824
825     if (DPA_InsertPtr(infoPtr->items, INT_MAX, newItem) == -1)
826     {
827         COMCTL32_Free(newItem);
828         return NULL;
829     }
830
831     return newItem;
832 }
833
834 /* Exact opposite of TREEVIEW_AllocateItem. In particular, it does not
835  * free item->pszText. */
836 static void
837 TREEVIEW_FreeItem(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *item)
838 {
839     DPA_DeletePtr(infoPtr->items, DPA_GetPtrIndex(infoPtr->items, item));
840     COMCTL32_Free(item);
841 }
842
843
844 /* Item Insertion *******************************************************/
845
846 /***************************************************************************
847  * This method inserts newItem before sibling as a child of parent.
848  * sibling can be NULL, but only if parent has no children.
849  */
850 static void
851 TREEVIEW_InsertBefore(TREEVIEW_ITEM *newItem, TREEVIEW_ITEM *sibling,
852                       TREEVIEW_ITEM *parent)
853 {
854     assert(newItem != NULL);
855     assert(parent != NULL);
856
857     if (sibling != NULL)
858     {
859         assert(sibling->parent == parent);
860
861         if (sibling->prevSibling != NULL)
862             sibling->prevSibling->nextSibling = newItem;
863
864         newItem->prevSibling = sibling->prevSibling;
865         sibling->prevSibling = newItem;
866     }
867     else
868        newItem->prevSibling = NULL;
869
870     newItem->nextSibling = sibling;
871
872     if (parent->firstChild == sibling)
873         parent->firstChild = newItem;
874
875     if (parent->lastChild == NULL)
876         parent->lastChild = newItem;
877 }
878
879 /***************************************************************************
880  * This method inserts newItem after sibling as a child of parent.
881  * sibling can be NULL, but only if parent has no children.
882  */
883 static void
884 TREEVIEW_InsertAfter(TREEVIEW_ITEM *newItem, TREEVIEW_ITEM *sibling,
885                      TREEVIEW_ITEM *parent)
886 {
887     assert(newItem != NULL);
888     assert(parent != NULL);
889
890     if (sibling != NULL)
891     {
892         assert(sibling->parent == parent);
893
894         if (sibling->nextSibling != NULL)
895             sibling->nextSibling->prevSibling = newItem;
896
897         newItem->nextSibling = sibling->nextSibling;
898         sibling->nextSibling = newItem;
899     }
900     else
901        newItem->nextSibling = NULL;
902
903     newItem->prevSibling = sibling;
904
905     if (parent->lastChild == sibling)
906         parent->lastChild = newItem;
907
908     if (parent->firstChild == NULL)
909         parent->firstChild = newItem;
910 }
911
912 static BOOL
913 TREEVIEW_DoSetItem(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *wineItem,
914                    const TVITEMEXA *tvItem)
915 {
916     UINT callbackClear = 0;
917     UINT callbackSet = 0;
918
919     /* Do this first in case it fails. */
920     if (tvItem->mask & TVIF_TEXT)
921     {
922         wineItem->textWidth = 0; /* force width recalculation */
923         if (tvItem->pszText != LPSTR_TEXTCALLBACKA)
924         {
925             int len = lstrlenA(tvItem->pszText) + 1;
926             LPSTR newText = COMCTL32_ReAlloc(wineItem->pszText, len);
927
928             if (newText == NULL) return FALSE;
929
930             callbackClear |= TVIF_TEXT;
931
932             wineItem->pszText = newText;
933             wineItem->cchTextMax = len;
934             lstrcpynA(wineItem->pszText, tvItem->pszText, len);
935         }
936         else
937         {
938             callbackSet |= TVIF_TEXT;
939
940             wineItem->pszText = COMCTL32_ReAlloc(wineItem->pszText,
941                                                  TEXT_CALLBACK_SIZE);
942             wineItem->cchTextMax = TEXT_CALLBACK_SIZE;
943         }
944     }
945
946     if (tvItem->mask & TVIF_CHILDREN)
947     {
948         wineItem->cChildren = tvItem->cChildren;
949
950         if (wineItem->cChildren == I_CHILDRENCALLBACK)
951             callbackSet |= TVIF_CHILDREN;
952         else
953             callbackClear |= TVIF_CHILDREN;
954     }
955
956     if (tvItem->mask & TVIF_IMAGE)
957     {
958         wineItem->iImage = tvItem->iImage;
959
960         if (wineItem->iImage == I_IMAGECALLBACK)
961             callbackSet |= TVIF_IMAGE;
962         else
963             callbackClear |= TVIF_IMAGE;
964     }
965
966     if (tvItem->mask & TVIF_SELECTEDIMAGE)
967     {
968         wineItem->iSelectedImage = tvItem->iSelectedImage;
969
970         if (wineItem->iSelectedImage == I_IMAGECALLBACK)
971             callbackSet |= TVIF_SELECTEDIMAGE;
972         else
973             callbackClear |= TVIF_SELECTEDIMAGE;
974     }
975
976     if (tvItem->mask & TVIF_PARAM)
977         wineItem->lParam = tvItem->lParam;
978
979     /* If the application sets TVIF_INTEGRAL without
980      * supplying a TVITEMEX structure, it's toast. */
981     if (tvItem->mask & TVIF_INTEGRAL)
982         wineItem->iIntegral = tvItem->iIntegral;
983
984     if (tvItem->mask & TVIF_STATE)
985     {
986         TRACE("prevstate,state,mask:%x,%x,%x\n", wineItem->state, tvItem->state,
987               tvItem->stateMask);
988         wineItem->state &= ~tvItem->stateMask;
989         wineItem->state |= (tvItem->state & tvItem->stateMask);
990     }
991
992     wineItem->callbackMask |= callbackSet;
993     wineItem->callbackMask &= ~callbackClear;
994
995     return TRUE;
996 }
997
998 /* Note that the new item is pre-zeroed. */
999 static LRESULT
1000 TREEVIEW_InsertItemA(TREEVIEW_INFO *infoPtr, LPARAM lParam)
1001 {
1002     const TVINSERTSTRUCTA *ptdi = (LPTVINSERTSTRUCTA) lParam;
1003     const TVITEMEXA *tvItem = &ptdi->DUMMYUNIONNAME.itemex;
1004     HTREEITEM insertAfter;
1005     TREEVIEW_ITEM *newItem, *parentItem;
1006     BOOL bTextUpdated = FALSE;
1007
1008     if (ptdi->hParent == TVI_ROOT || ptdi->hParent == 0)
1009     {
1010         parentItem = infoPtr->root;
1011     }
1012     else
1013     {
1014         parentItem = ptdi->hParent;
1015
1016         if (!TREEVIEW_ValidItem(infoPtr, parentItem))
1017         {
1018             WARN("invalid parent %p\n", parentItem);
1019             return (LRESULT)(HTREEITEM)NULL;
1020         }
1021     }
1022
1023     insertAfter = ptdi->hInsertAfter;
1024
1025     /* Validate this now for convenience. */
1026     switch ((DWORD)insertAfter)
1027     {
1028     case (DWORD)TVI_FIRST:
1029     case (DWORD)TVI_LAST:
1030     case (DWORD)TVI_SORT:
1031         break;
1032
1033     default:
1034         if (!TREEVIEW_ValidItem(infoPtr, insertAfter) ||
1035             insertAfter->parent != parentItem)
1036         {
1037             WARN("invalid insert after %p\n", insertAfter);
1038             insertAfter = TVI_LAST;
1039         }
1040     }
1041
1042     TRACE("parent %p position %p: '%s'\n", parentItem, insertAfter,
1043           (tvItem->mask & TVIF_TEXT)
1044           ? ((tvItem->pszText == LPSTR_TEXTCALLBACKA) ? "<callback>"
1045              : tvItem->pszText)
1046           : "<no label>");
1047
1048     newItem = TREEVIEW_AllocateItem(infoPtr);
1049     if (newItem == NULL)
1050         return (LRESULT)(HTREEITEM)NULL;
1051
1052     newItem->parent = parentItem;
1053     newItem->iIntegral = 1;
1054
1055     if (!TREEVIEW_DoSetItem(infoPtr, newItem, tvItem))
1056         return (LRESULT)(HTREEITEM)NULL;
1057
1058     /* After this point, nothing can fail. (Except for TVI_SORT.) */
1059
1060     infoPtr->uNumItems++;
1061
1062     switch ((DWORD)insertAfter)
1063     {
1064     case (DWORD)TVI_FIRST:
1065         TREEVIEW_InsertBefore(newItem, parentItem->firstChild, parentItem);
1066         if (infoPtr->firstVisible == parentItem->firstChild)
1067             TREEVIEW_SetFirstVisible(infoPtr, newItem, TRUE);
1068         break;
1069
1070     case (DWORD)TVI_LAST:
1071         TREEVIEW_InsertAfter(newItem, parentItem->lastChild, parentItem);
1072         break;
1073
1074         /* hInsertAfter names a specific item we want to insert after */
1075     default:
1076         TREEVIEW_InsertAfter(newItem, insertAfter, insertAfter->parent);
1077         break;
1078
1079     case (DWORD)TVI_SORT:
1080         {
1081             TREEVIEW_ITEM *aChild;
1082             TREEVIEW_ITEM *previousChild = NULL;
1083             BOOL bItemInserted = FALSE;
1084
1085             aChild = parentItem->firstChild;
1086
1087             bTextUpdated = TRUE;
1088             TREEVIEW_UpdateDispInfo(infoPtr, newItem, TVIF_TEXT);
1089
1090             /* Iterate the parent children to see where we fit in */
1091             while (aChild != NULL)
1092             {
1093                 INT comp;
1094
1095                 TREEVIEW_UpdateDispInfo(infoPtr, aChild, TVIF_TEXT);
1096                 comp = lstrcmpA(newItem->pszText, aChild->pszText);
1097
1098                 if (comp < 0)   /* we are smaller than the current one */
1099                 {
1100                     TREEVIEW_InsertBefore(newItem, aChild, parentItem);
1101                     bItemInserted = TRUE;
1102                     break;
1103                 }
1104                 else if (comp > 0)      /* we are bigger than the current one */
1105                 {
1106                     previousChild = aChild;
1107
1108                     /* This will help us to exit if there is no more sibling */
1109                     aChild = (aChild->nextSibling == 0)
1110                         ? NULL  
1111                         : aChild->nextSibling;
1112
1113                     /* Look at the next item */
1114                     continue;
1115                 }
1116                 else if (comp == 0)
1117                 {
1118                     /* 
1119                      * An item with this name is already existing, therefore,  
1120                      * we add after the one we found 
1121                      */
1122                     TREEVIEW_InsertAfter(newItem, aChild, parentItem);
1123                     bItemInserted = TRUE;
1124                     break;
1125                 }
1126             }
1127
1128             /* 
1129              * we reach the end of the child list and the item has not
1130              * yet been inserted, therefore, insert it after the last child.
1131              */
1132             if ((!bItemInserted) && (aChild == NULL))
1133                 TREEVIEW_InsertAfter(newItem, previousChild, parentItem);
1134
1135             break;
1136         }
1137     }
1138
1139
1140     TRACE("new item %p; parent %p, mask %x\n", newItem,
1141           newItem->parent, tvItem->mask);
1142
1143     newItem->iLevel = newItem->parent->iLevel + 1;
1144
1145     if (newItem->parent->cChildren == 0)
1146         newItem->parent->cChildren = 1;
1147
1148     if (infoPtr->dwStyle & TVS_CHECKBOXES)
1149     {
1150         if (STATEIMAGEINDEX(newItem->state) == 0)
1151             newItem->state |= INDEXTOSTATEIMAGEMASK(1);
1152     }
1153
1154     if (infoPtr->firstVisible == NULL)
1155         infoPtr->firstVisible = newItem;
1156
1157     TREEVIEW_VerifyTree(infoPtr);
1158
1159     if (parentItem == infoPtr->root ||
1160         (ISVISIBLE(parentItem) && parentItem->state & TVIS_EXPANDED))
1161     {
1162        TREEVIEW_ITEM *item;
1163        TREEVIEW_ITEM *prev = TREEVIEW_GetPrevListItem(infoPtr, newItem);
1164
1165        TREEVIEW_RecalculateVisibleOrder(infoPtr, prev);
1166        TREEVIEW_ComputeItemInternalMetrics(infoPtr, newItem);
1167
1168        if (!bTextUpdated)
1169           TREEVIEW_UpdateDispInfo(infoPtr, newItem, TVIF_TEXT);
1170
1171        TREEVIEW_ComputeTextWidth(infoPtr, newItem, 0);
1172        TREEVIEW_UpdateScrollBars(infoPtr);
1173     /*
1174      * if the item was inserted in a visible part of the tree, 
1175      * invalidate it, as well as those after it
1176      */
1177        for (item = newItem;
1178             item != NULL;
1179             item = TREEVIEW_GetNextListItem(infoPtr, item))
1180           TREEVIEW_Invalidate(infoPtr, item);
1181     }
1182     else
1183     {
1184        newItem->visibleOrder = -1;
1185
1186        /* refresh treeview if newItem is the first item inserted under parentItem */
1187        if (ISVISIBLE(parentItem) && newItem->prevSibling == newItem->nextSibling)
1188        {
1189           /* parent got '+' - update it */
1190           TREEVIEW_Invalidate(infoPtr, parentItem);
1191        }
1192     }
1193
1194     return (LRESULT)newItem;
1195 }
1196
1197
1198 static LRESULT
1199 TREEVIEW_InsertItemW(TREEVIEW_INFO *infoPtr, LPARAM lParam)
1200 {
1201     TVINSERTSTRUCTW *tvisW;
1202     TVINSERTSTRUCTA tvisA;
1203     LRESULT lRes;
1204
1205     tvisW = (LPTVINSERTSTRUCTW) lParam;
1206
1207     tvisA.hParent = tvisW->hParent;
1208     tvisA.hInsertAfter = tvisW->hInsertAfter;
1209
1210     tvisA.DUMMYUNIONNAME.item.mask = tvisW->DUMMYUNIONNAME.item.mask;
1211     tvisA.DUMMYUNIONNAME.item.hItem = tvisW->DUMMYUNIONNAME.item.hItem;
1212     tvisA.DUMMYUNIONNAME.item.state = tvisW->DUMMYUNIONNAME.item.state;
1213     tvisA.DUMMYUNIONNAME.item.stateMask = tvisW->DUMMYUNIONNAME.item.stateMask;
1214     tvisA.DUMMYUNIONNAME.item.cchTextMax =
1215         tvisW->DUMMYUNIONNAME.item.cchTextMax;
1216
1217     if (tvisW->DUMMYUNIONNAME.item.pszText)
1218     {
1219         if (tvisW->DUMMYUNIONNAME.item.pszText != LPSTR_TEXTCALLBACKW)
1220         {
1221             int len = WideCharToMultiByte( CP_ACP, 0, tvisW->DUMMYUNIONNAME.item.pszText, -1,
1222                                            NULL, 0, NULL, NULL );
1223             tvisA.DUMMYUNIONNAME.item.pszText = COMCTL32_Alloc(len);
1224             WideCharToMultiByte( CP_ACP, 0, tvisW->DUMMYUNIONNAME.item.pszText, -1,
1225                                  tvisA.DUMMYUNIONNAME.item.pszText, len, NULL, NULL );
1226         }
1227         else
1228         {
1229             tvisA.DUMMYUNIONNAME.item.pszText = LPSTR_TEXTCALLBACKA;
1230             tvisA.DUMMYUNIONNAME.item.cchTextMax = 0;
1231         }
1232     }
1233
1234     tvisA.DUMMYUNIONNAME.item.iImage = tvisW->DUMMYUNIONNAME.item.iImage;
1235     tvisA.DUMMYUNIONNAME.item.iSelectedImage =
1236         tvisW->DUMMYUNIONNAME.item.iSelectedImage;
1237     tvisA.DUMMYUNIONNAME.item.cChildren = tvisW->DUMMYUNIONNAME.item.cChildren;
1238     tvisA.DUMMYUNIONNAME.item.lParam = tvisW->DUMMYUNIONNAME.item.lParam;
1239
1240     lRes = TREEVIEW_InsertItemA(infoPtr, (LPARAM)&tvisA);
1241
1242     if (tvisA.DUMMYUNIONNAME.item.pszText != LPSTR_TEXTCALLBACKA)
1243     {
1244         COMCTL32_Free(tvisA.DUMMYUNIONNAME.item.pszText);
1245     }
1246
1247     return lRes;
1248
1249 }
1250
1251
1252 /* Item Deletion ************************************************************/
1253 static void
1254 TREEVIEW_RemoveItem(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *wineItem);
1255
1256 static void
1257 TREEVIEW_RemoveAllChildren(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *parentItem)
1258 {
1259     TREEVIEW_ITEM *kill = parentItem->firstChild;
1260
1261     while (kill != NULL)
1262     {
1263         TREEVIEW_ITEM *next = kill->nextSibling;
1264
1265         TREEVIEW_RemoveItem(infoPtr, kill);
1266
1267         kill = next;
1268     }
1269
1270     assert(parentItem->cChildren <= 0); /* I_CHILDRENCALLBACK or 0 */
1271     assert(parentItem->firstChild == NULL);
1272     assert(parentItem->lastChild == NULL);
1273 }
1274
1275 static void
1276 TREEVIEW_UnlinkItem(TREEVIEW_ITEM *item)
1277 {
1278     TREEVIEW_ITEM *parentItem = item->parent;
1279
1280     assert(item != NULL);
1281     assert(item->parent != NULL); /* i.e. it must not be the root */
1282
1283     if (parentItem->firstChild == item)
1284         parentItem->firstChild = item->nextSibling;
1285
1286     if (parentItem->lastChild == item)
1287         parentItem->lastChild = item->prevSibling;
1288
1289     if (parentItem->firstChild == NULL && parentItem->lastChild == NULL
1290         && parentItem->cChildren > 0)
1291         parentItem->cChildren = 0;
1292
1293     if (item->prevSibling)
1294         item->prevSibling->nextSibling = item->nextSibling;
1295
1296     if (item->nextSibling)
1297         item->nextSibling->prevSibling = item->prevSibling;
1298 }
1299
1300 static void
1301 TREEVIEW_RemoveItem(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *wineItem)
1302 {
1303     TRACE("%p, (%s)\n", wineItem, TREEVIEW_ItemName(wineItem));
1304
1305     TREEVIEW_SendTreeviewNotify(infoPtr, TVN_DELETEITEMA,
1306                                 TVIF_HANDLE | TVIF_PARAM, 0, wineItem, 0);
1307
1308     if (wineItem->firstChild)
1309         TREEVIEW_RemoveAllChildren(infoPtr, wineItem);
1310
1311     TREEVIEW_UnlinkItem(wineItem);
1312
1313     infoPtr->uNumItems--;
1314
1315     if (wineItem->pszText != LPSTR_TEXTCALLBACKA)
1316         COMCTL32_Free(wineItem->pszText);
1317
1318     TREEVIEW_FreeItem(infoPtr, wineItem);
1319 }
1320
1321
1322 /* Empty out the tree. */
1323 static void
1324 TREEVIEW_RemoveTree(TREEVIEW_INFO *infoPtr)
1325 {
1326     TREEVIEW_RemoveAllChildren(infoPtr, infoPtr->root);
1327
1328     assert(infoPtr->uNumItems == 0);    /* root isn't counted in uNumItems */
1329 }
1330
1331 static LRESULT
1332 TREEVIEW_DeleteItem(TREEVIEW_INFO *infoPtr, HTREEITEM wineItem)
1333 {
1334     TREEVIEW_ITEM *oldSelection = infoPtr->selectedItem;
1335     TREEVIEW_ITEM *newSelection = oldSelection;
1336     TREEVIEW_ITEM *newFirstVisible = NULL;
1337     TREEVIEW_ITEM *parent, *prev = NULL;
1338     BOOL visible = FALSE;
1339
1340     if (wineItem == TVI_ROOT)
1341     {
1342         TRACE("TVI_ROOT\n");
1343         parent = infoPtr->root;
1344         newSelection = NULL;
1345         visible = TRUE;
1346         TREEVIEW_RemoveTree(infoPtr);
1347     }
1348     else
1349     {
1350         if (!TREEVIEW_ValidItem(infoPtr, wineItem))
1351             return FALSE;
1352
1353         TRACE("%p (%s)\n", wineItem, TREEVIEW_ItemName(wineItem));
1354         parent = wineItem->parent;
1355
1356         if (ISVISIBLE(wineItem))
1357         {
1358             prev = TREEVIEW_GetPrevListItem(infoPtr, wineItem);
1359             visible = TRUE;
1360         }
1361
1362         if (infoPtr->selectedItem != NULL
1363             && (wineItem == infoPtr->selectedItem
1364                 || TREEVIEW_IsChildOf(wineItem, infoPtr->selectedItem)))
1365         {
1366             if (wineItem->nextSibling)
1367                 newSelection = wineItem->nextSibling;
1368             else if (wineItem->parent != infoPtr->root)
1369                 newSelection = wineItem->parent;
1370         }
1371
1372         if (infoPtr->firstVisible == wineItem)
1373         {
1374             if (wineItem->nextSibling)
1375                newFirstVisible = wineItem->nextSibling;
1376             else if (wineItem->prevSibling)
1377                newFirstVisible = wineItem->prevSibling;
1378             else if (wineItem->parent != infoPtr->root)
1379                newFirstVisible = wineItem->parent;
1380         }
1381         else
1382             newFirstVisible = infoPtr->firstVisible;
1383
1384         TREEVIEW_RemoveItem(infoPtr, wineItem);
1385     }
1386
1387     /* Don't change if somebody else already has. */
1388     if (oldSelection == infoPtr->selectedItem)
1389     {
1390         if (TREEVIEW_ValidItem(infoPtr, newSelection))
1391             TREEVIEW_DoSelectItem(infoPtr, TVGN_CARET, newSelection, TVC_UNKNOWN);
1392         else
1393             infoPtr->selectedItem = 0;
1394     }
1395
1396     /* Validate insertMark dropItem.
1397      * hotItem ??? - used for comparison only.
1398      */
1399     if (!TREEVIEW_ValidItem(infoPtr, infoPtr->insertMarkItem))
1400         infoPtr->insertMarkItem = 0;
1401
1402     if (!TREEVIEW_ValidItem(infoPtr, infoPtr->dropItem))
1403         infoPtr->dropItem = 0;
1404
1405     if (!TREEVIEW_ValidItem(infoPtr, newFirstVisible))
1406         newFirstVisible = infoPtr->root->firstChild;
1407
1408     TREEVIEW_VerifyTree(infoPtr);
1409
1410
1411     if (visible)
1412     {
1413        TREEVIEW_RecalculateVisibleOrder(infoPtr, prev);
1414        TREEVIEW_SetFirstVisible(infoPtr, newFirstVisible, TRUE);
1415        TREEVIEW_UpdateScrollBars(infoPtr);
1416        TREEVIEW_Invalidate(infoPtr, NULL);
1417     }
1418     else if (ISVISIBLE(parent) && !TREEVIEW_HasChildren(infoPtr, parent))
1419     {
1420        /* parent lost '+/-' - update it */
1421        TREEVIEW_Invalidate(infoPtr, parent);
1422     }
1423
1424     return TRUE;
1425 }
1426
1427
1428 /* Get/Set Messages *********************************************************/
1429 static LRESULT
1430 TREEVIEW_SetRedraw(TREEVIEW_INFO* infoPtr, WPARAM wParam, LPARAM lParam)
1431 {
1432   if(wParam)
1433     infoPtr->bRedraw = TRUE;
1434   else
1435     infoPtr->bRedraw = FALSE;
1436
1437   return 0;
1438 }
1439
1440 static LRESULT
1441 TREEVIEW_GetIndent(TREEVIEW_INFO *infoPtr)
1442 {
1443     TRACE("\n");
1444     return infoPtr->uIndent;
1445 }
1446
1447 static LRESULT
1448 TREEVIEW_SetIndent(TREEVIEW_INFO *infoPtr, UINT newIndent)
1449 {
1450     TRACE("\n");
1451
1452     if (newIndent < MINIMUM_INDENT)
1453         newIndent = MINIMUM_INDENT;
1454
1455     if (infoPtr->uIndent != newIndent)
1456     {
1457         infoPtr->uIndent = newIndent;
1458         TREEVIEW_UpdateSubTree(infoPtr, infoPtr->root);
1459         TREEVIEW_UpdateScrollBars(infoPtr);
1460         TREEVIEW_Invalidate(infoPtr, NULL);
1461     }
1462
1463     return 0;
1464 }
1465
1466
1467 static LRESULT
1468 TREEVIEW_GetToolTips(TREEVIEW_INFO *infoPtr)
1469 {
1470     TRACE("\n");
1471     return infoPtr->hwndToolTip;
1472 }
1473
1474 static LRESULT
1475 TREEVIEW_SetToolTips(TREEVIEW_INFO *infoPtr, HWND hwndTT)
1476 {
1477     HWND prevToolTip;
1478
1479     TRACE("\n");
1480     prevToolTip = infoPtr->hwndToolTip;
1481     infoPtr->hwndToolTip = hwndTT;
1482
1483     return prevToolTip;
1484 }
1485
1486
1487 static LRESULT
1488 TREEVIEW_GetScrollTime(TREEVIEW_INFO *infoPtr)
1489 {
1490     return infoPtr->uScrollTime;
1491 }
1492
1493 static LRESULT
1494 TREEVIEW_SetScrollTime(TREEVIEW_INFO *infoPtr, UINT uScrollTime)
1495 {
1496     UINT uOldScrollTime = infoPtr->uScrollTime;
1497
1498     infoPtr->uScrollTime = min(uScrollTime, 100);
1499
1500     return uOldScrollTime;
1501 }
1502
1503
1504 static LRESULT
1505 TREEVIEW_GetImageList(TREEVIEW_INFO *infoPtr, WPARAM wParam)
1506 {
1507     TRACE("\n");
1508
1509     switch (wParam)
1510     {
1511     case (WPARAM)TVSIL_NORMAL:
1512         return (LRESULT)infoPtr->himlNormal;
1513
1514     case (WPARAM)TVSIL_STATE:
1515         return (LRESULT)infoPtr->himlState;
1516
1517     default:
1518         return 0;
1519     }
1520 }
1521
1522 static LRESULT
1523 TREEVIEW_SetImageList(TREEVIEW_INFO *infoPtr, WPARAM wParam, HIMAGELIST himlNew)
1524 {
1525     HIMAGELIST himlOld = 0;
1526     int oldWidth  = infoPtr->normalImageWidth;
1527     int oldHeight = infoPtr->normalImageHeight;
1528
1529
1530     TRACE("%x,%p\n", wParam, himlNew);
1531
1532     switch (wParam)
1533     {
1534     case (WPARAM)TVSIL_NORMAL:
1535         himlOld = infoPtr->himlNormal;
1536         infoPtr->himlNormal = himlNew;
1537
1538         if (himlNew != NULL)
1539             ImageList_GetIconSize(himlNew, &infoPtr->normalImageWidth,
1540                                   &infoPtr->normalImageHeight);
1541         else
1542         {
1543             infoPtr->normalImageWidth = 0;
1544             infoPtr->normalImageHeight = 0;
1545         }
1546
1547         break;
1548
1549     case (WPARAM)TVSIL_STATE:
1550         himlOld = infoPtr->himlState;
1551         infoPtr->himlState = himlNew;
1552
1553         if (himlNew != NULL)
1554             ImageList_GetIconSize(himlNew, &infoPtr->stateImageWidth,
1555                                   &infoPtr->stateImageHeight);
1556         else
1557         {
1558             infoPtr->stateImageWidth = 0;
1559             infoPtr->stateImageHeight = 0;
1560         }
1561
1562         break;
1563     }
1564
1565     if (oldWidth != infoPtr->normalImageWidth ||
1566         oldHeight != infoPtr->normalImageHeight)
1567     {
1568        TREEVIEW_UpdateSubTree(infoPtr, infoPtr->root);
1569        TREEVIEW_UpdateScrollBars(infoPtr);
1570     }
1571
1572     TREEVIEW_Invalidate(infoPtr, NULL);
1573
1574     return (LRESULT)himlOld;
1575 }
1576
1577 /* Compute the natural height (based on the font size) for items. */
1578 static UINT
1579 TREEVIEW_NaturalHeight(TREEVIEW_INFO *infoPtr)
1580 {
1581     TEXTMETRICA tm;
1582     HDC hdc = GetDC(0);
1583     HFONT hOldFont = SelectObject(hdc, infoPtr->hFont);
1584
1585     GetTextMetricsA(hdc, &tm);
1586
1587     SelectObject(hdc, hOldFont);
1588     ReleaseDC(0, hdc);
1589
1590     /* The 16 is a hack because our fonts are tiny. */
1591     /* add 2 for the focus border and 1 more for margin some apps assume */
1592     return max(16, tm.tmHeight + tm.tmExternalLeading + 3);
1593 }
1594
1595 static LRESULT
1596 TREEVIEW_SetItemHeight(TREEVIEW_INFO *infoPtr, INT newHeight)
1597 {
1598     INT prevHeight = infoPtr->uItemHeight;
1599
1600     TRACE("%d \n", newHeight);
1601     if (newHeight == -1)
1602     {
1603         infoPtr->uItemHeight = TREEVIEW_NaturalHeight(infoPtr);
1604         infoPtr->bHeightSet = FALSE;
1605     }
1606     else
1607     {
1608         infoPtr->uItemHeight = newHeight;
1609         infoPtr->bHeightSet = TRUE;
1610     }
1611
1612     /* Round down, unless we support odd ("non even") heights. */
1613     if (!(infoPtr->dwStyle) & TVS_NONEVENHEIGHT)
1614         infoPtr->uItemHeight &= ~1;
1615
1616     if (infoPtr->uItemHeight != prevHeight)
1617     {
1618         TREEVIEW_RecalculateVisibleOrder(infoPtr, NULL);
1619         TREEVIEW_UpdateScrollBars(infoPtr);
1620         TREEVIEW_Invalidate(infoPtr, NULL);
1621     }
1622
1623     return prevHeight;
1624 }
1625
1626 static LRESULT
1627 TREEVIEW_GetItemHeight(TREEVIEW_INFO *infoPtr)
1628 {
1629     TRACE("\n");
1630     return infoPtr->uItemHeight;
1631 }
1632
1633
1634 static LRESULT
1635 TREEVIEW_GetFont(TREEVIEW_INFO *infoPtr)
1636 {
1637     TRACE("%x\n", infoPtr->hFont);
1638     return infoPtr->hFont;
1639 }
1640
1641
1642 static INT CALLBACK
1643 TREEVIEW_ResetTextWidth(LPVOID pItem, DWORD unused)
1644 {
1645     (void)unused;
1646
1647     ((TREEVIEW_ITEM *)pItem)->textWidth = 0;
1648
1649     return 1;
1650 }
1651
1652 static LRESULT
1653 TREEVIEW_SetFont(TREEVIEW_INFO *infoPtr, HFONT hFont, BOOL bRedraw)
1654 {
1655     UINT uHeight = infoPtr->uItemHeight;
1656
1657     TRACE("%x %i\n", hFont, bRedraw);
1658
1659     infoPtr->hFont = hFont ? hFont : GetStockObject(SYSTEM_FONT);
1660
1661     DeleteObject(infoPtr->hBoldFont);
1662     infoPtr->hBoldFont = TREEVIEW_CreateBoldFont(infoPtr->hFont);
1663
1664     if (!infoPtr->bHeightSet)
1665         infoPtr->uItemHeight = TREEVIEW_NaturalHeight(infoPtr);
1666
1667     if (uHeight != infoPtr->uItemHeight)
1668        TREEVIEW_RecalculateVisibleOrder(infoPtr, NULL);
1669
1670     DPA_EnumCallback(infoPtr->items, TREEVIEW_ResetTextWidth, 0);
1671
1672     TREEVIEW_UpdateSubTree(infoPtr, infoPtr->root);
1673     TREEVIEW_UpdateScrollBars(infoPtr);
1674
1675     if (bRedraw)
1676         TREEVIEW_Invalidate(infoPtr, NULL);
1677
1678     return 0;
1679 }
1680
1681
1682 static LRESULT
1683 TREEVIEW_GetLineColor(TREEVIEW_INFO *infoPtr)
1684 {
1685     TRACE("\n");
1686     return (LRESULT)infoPtr->clrLine;
1687 }
1688
1689 static LRESULT
1690 TREEVIEW_SetLineColor(TREEVIEW_INFO *infoPtr, COLORREF color)
1691 {
1692     COLORREF prevColor = infoPtr->clrLine;
1693
1694     TRACE("\n");
1695     infoPtr->clrLine = color;
1696     return (LRESULT)prevColor;
1697 }
1698
1699
1700 static LRESULT
1701 TREEVIEW_GetTextColor(TREEVIEW_INFO *infoPtr)
1702 {
1703     TRACE("\n");
1704     return (LRESULT)infoPtr->clrText;
1705 }
1706
1707 static LRESULT
1708 TREEVIEW_SetTextColor(TREEVIEW_INFO *infoPtr, COLORREF color)
1709 {
1710     COLORREF prevColor = infoPtr->clrText;
1711
1712     TRACE("\n");
1713     infoPtr->clrText = color;
1714
1715     if (infoPtr->clrText != prevColor)
1716         TREEVIEW_Invalidate(infoPtr, NULL);
1717
1718     return (LRESULT)prevColor;
1719 }
1720
1721
1722 static LRESULT
1723 TREEVIEW_GetBkColor(TREEVIEW_INFO *infoPtr)
1724 {
1725     TRACE("\n");
1726     return (LRESULT)infoPtr->clrBk;
1727 }
1728
1729 static LRESULT
1730 TREEVIEW_SetBkColor(TREEVIEW_INFO *infoPtr, COLORREF newColor)
1731 {
1732     COLORREF prevColor = infoPtr->clrBk;
1733
1734     TRACE("\n");
1735     infoPtr->clrBk = newColor;
1736
1737     if (newColor != prevColor)
1738         TREEVIEW_Invalidate(infoPtr, NULL);
1739
1740     return (LRESULT)prevColor;
1741 }
1742
1743
1744 static LRESULT
1745 TREEVIEW_GetInsertMarkColor(TREEVIEW_INFO *infoPtr)
1746 {
1747     TRACE("\n");
1748     return (LRESULT)infoPtr->clrInsertMark;
1749 }
1750
1751 static LRESULT
1752 TREEVIEW_SetInsertMarkColor(TREEVIEW_INFO *infoPtr, COLORREF color)
1753 {
1754     COLORREF prevColor = infoPtr->clrInsertMark;
1755
1756     TRACE("%lx\n", color);
1757     infoPtr->clrInsertMark = color;
1758
1759     return (LRESULT)prevColor;
1760 }
1761
1762
1763 static LRESULT
1764 TREEVIEW_SetInsertMark(TREEVIEW_INFO *infoPtr, BOOL wParam, HTREEITEM item)
1765 {
1766     TRACE("%d %p\n", wParam, item);
1767
1768     if (!TREEVIEW_ValidItem(infoPtr, item))
1769         return 0;
1770
1771     infoPtr->insertBeforeorAfter = wParam;
1772     infoPtr->insertMarkItem = item;
1773
1774     TREEVIEW_Invalidate(infoPtr, NULL);
1775
1776     return 1;
1777 }
1778
1779
1780 /************************************************************************
1781  * Some serious braindamage here. lParam is a pointer to both the
1782  * input HTREEITEM and the output RECT.
1783  */
1784 static LRESULT
1785 TREEVIEW_GetItemRect(TREEVIEW_INFO *infoPtr, BOOL fTextRect, LPRECT lpRect)
1786 {
1787     TREEVIEW_ITEM *wineItem;
1788     const HTREEITEM *pItem = (HTREEITEM *)lpRect;
1789
1790     TRACE("\n");
1791     /*
1792      * validate parameters
1793      */
1794     if (pItem == NULL)
1795         return FALSE;
1796
1797     wineItem = *pItem;
1798     if (!TREEVIEW_ValidItem(infoPtr, wineItem) || !ISVISIBLE(wineItem))
1799         return FALSE;
1800
1801     /* 
1802      * If wParam is TRUE return the text size otherwise return 
1803      * the whole item size        
1804      */
1805     if (fTextRect)
1806     {
1807         /* Windows does not send TVN_GETDISPINFO here. */
1808
1809         lpRect->top = wineItem->rect.top;
1810         lpRect->bottom = wineItem->rect.bottom;
1811
1812         lpRect->left = wineItem->textOffset;
1813         lpRect->right = wineItem->textOffset + wineItem->textWidth;
1814     }
1815     else
1816     {
1817         *lpRect = wineItem->rect;
1818     }
1819
1820     TRACE("%s [L:%d R:%d T:%d B:%d]\n", fTextRect ? "text" : "item",
1821           lpRect->left, lpRect->right, lpRect->top, lpRect->bottom);
1822
1823     return TRUE;
1824 }
1825
1826 static inline LRESULT
1827 TREEVIEW_GetVisibleCount(TREEVIEW_INFO *infoPtr)
1828 {
1829     /* Suprise! This does not take integral height into account. */
1830     return infoPtr->clientHeight / infoPtr->uItemHeight;
1831 }
1832
1833
1834 static LRESULT
1835 TREEVIEW_GetItemA(TREEVIEW_INFO *infoPtr, LPTVITEMEXA tvItem)
1836 {
1837     TREEVIEW_ITEM *wineItem;
1838
1839     wineItem = tvItem->hItem;
1840     if (!TREEVIEW_ValidItem(infoPtr, wineItem))
1841         return FALSE;
1842
1843     TREEVIEW_UpdateDispInfo(infoPtr, wineItem, tvItem->mask);
1844
1845     if (tvItem->mask & TVIF_CHILDREN)
1846         tvItem->cChildren = wineItem->cChildren;
1847
1848     if (tvItem->mask & TVIF_HANDLE)
1849         tvItem->hItem = wineItem;
1850
1851     if (tvItem->mask & TVIF_IMAGE)
1852         tvItem->iImage = wineItem->iImage;
1853
1854     if (tvItem->mask & TVIF_INTEGRAL)
1855         tvItem->iIntegral = wineItem->iIntegral;
1856
1857     /* undocumented: windows ignores TVIF_PARAM and
1858      * * always sets lParam
1859      */
1860     tvItem->lParam = wineItem->lParam;
1861
1862     if (tvItem->mask & TVIF_SELECTEDIMAGE)
1863         tvItem->iSelectedImage = wineItem->iSelectedImage;
1864
1865     if (tvItem->mask & TVIF_STATE)
1866         tvItem->state = wineItem->state & tvItem->stateMask;
1867
1868     if (tvItem->mask & TVIF_TEXT)
1869         lstrcpynA(tvItem->pszText, wineItem->pszText, tvItem->cchTextMax);
1870
1871     TRACE("item <%p>, txt %p, img %p, mask %x\n",
1872           wineItem, tvItem->pszText, &tvItem->iImage, tvItem->mask);
1873
1874     return TRUE;
1875 }
1876
1877 /* Beware MSDN Library Visual Studio 6.0. It says -1 on failure, 0 on success,
1878  * which is wrong. */
1879 static LRESULT
1880 TREEVIEW_SetItemA(TREEVIEW_INFO *infoPtr, LPTVITEMEXA tvItem)
1881 {
1882     TREEVIEW_ITEM *wineItem;
1883     TREEVIEW_ITEM originalItem;
1884
1885     wineItem = tvItem->hItem;
1886
1887     TRACE("item %d,mask %x\n", TREEVIEW_GetItemIndex(infoPtr, wineItem),
1888           tvItem->mask);
1889
1890     if (!TREEVIEW_ValidItem(infoPtr, wineItem))
1891         return FALSE;
1892
1893     if (!TREEVIEW_DoSetItem(infoPtr, wineItem, tvItem))
1894         return FALSE;
1895
1896     /* store the orignal item values */
1897     originalItem = *wineItem;
1898
1899     /* If the text or TVIS_BOLD was changed, and it is visible, recalculate. */
1900     if ((tvItem->mask & TVIF_TEXT
1901          || (tvItem->mask & TVIF_STATE && tvItem->stateMask & TVIS_BOLD))
1902         && ISVISIBLE(wineItem))
1903     {
1904         TREEVIEW_UpdateDispInfo(infoPtr, wineItem, TVIF_TEXT);
1905         TREEVIEW_ComputeTextWidth(infoPtr, wineItem, 0);
1906     }
1907
1908     if (tvItem->mask != 0 && ISVISIBLE(wineItem))
1909     {
1910         /* The refresh updates everything, but we can't wait until then. */
1911         TREEVIEW_ComputeItemInternalMetrics(infoPtr, wineItem);
1912
1913         /* if any of the items values changed, redraw the item */
1914         if(memcmp(&originalItem, wineItem, sizeof(TREEVIEW_ITEM)))
1915         {
1916             if (tvItem->mask & TVIF_INTEGRAL)
1917             {
1918                 TREEVIEW_RecalculateVisibleOrder(infoPtr, wineItem);
1919                 TREEVIEW_UpdateScrollBars(infoPtr);
1920
1921                 TREEVIEW_Invalidate(infoPtr, NULL);
1922             }
1923             else
1924             {
1925                 TREEVIEW_UpdateScrollBars(infoPtr);
1926                 TREEVIEW_Invalidate(infoPtr, wineItem);
1927             }
1928         }
1929     }
1930
1931     return TRUE;
1932 }
1933
1934 static LRESULT
1935 TREEVIEW_GetItemW(TREEVIEW_INFO *infoPtr, LPTVITEMEXA tvItem)
1936 {
1937     TREEVIEW_ITEM *wineItem;
1938     INT         iItem;
1939     iItem = (INT)tvItem->hItem;
1940
1941     wineItem = tvItem->hItem;
1942     if(!TREEVIEW_ValidItem (infoPtr, wineItem))
1943         return FALSE;
1944
1945     TREEVIEW_UpdateDispInfo(infoPtr, wineItem, tvItem->mask);
1946
1947     if (tvItem->mask & TVIF_CHILDREN) {
1948         if (TVIF_CHILDREN==I_CHILDRENCALLBACK)
1949             FIXME("I_CHILDRENCALLBACK not supported\n");
1950         tvItem->cChildren = wineItem->cChildren;
1951     }
1952
1953     if (tvItem->mask & TVIF_HANDLE) {
1954         tvItem->hItem = wineItem;
1955     }
1956     if (tvItem->mask & TVIF_IMAGE) {
1957         tvItem->iImage = wineItem->iImage;
1958     }
1959     if (tvItem->mask & TVIF_INTEGRAL) {
1960         tvItem->iIntegral = wineItem->iIntegral;
1961     }
1962     /* undocumented: windows ignores TVIF_PARAM and
1963      * always sets lParam           */
1964     tvItem->lParam = wineItem->lParam;
1965     if (tvItem->mask & TVIF_SELECTEDIMAGE) {
1966         tvItem->iSelectedImage = wineItem->iSelectedImage;
1967     }
1968     if (tvItem->mask & TVIF_STATE) {
1969         tvItem->state = wineItem->state & tvItem->stateMask;
1970     }
1971 #if 0
1972     if (tvItem->mask & TVIF_TEXT) {
1973         if (wineItem->pszText == LPSTR_TEXTCALLBACKW) {
1974             tvItem->pszText = LPSTR_TEXTCALLBACKW;  /* FIXME:send notification? */
1975             ERR(" GetItem called with LPSTR_TEXTCALLBACK\n");
1976         }
1977         else if (wineItem->pszText) {
1978             lstrcpynAtoW(tvItem->pszText, wineItem->pszText, tvItem->cchTextMax);
1979         }
1980     }
1981 #endif
1982     wineItem->pszText = NULL;
1983     TRACE("item %d<%p>, txt %p, img %p, action %x\n",
1984         iItem, tvItem, tvItem->pszText, &tvItem->iImage, tvItem->mask);
1985     return TRUE;
1986 }
1987
1988 static LRESULT
1989 TREEVIEW_GetItemState(TREEVIEW_INFO *infoPtr, HTREEITEM wineItem, UINT mask)
1990 {
1991     TRACE("\n");
1992
1993     if (!wineItem || !TREEVIEW_ValidItem(infoPtr, wineItem))
1994         return 0;
1995
1996     return (wineItem->state & mask);
1997 }
1998
1999 static LRESULT
2000 TREEVIEW_GetNextItem(TREEVIEW_INFO *infoPtr, UINT which, HTREEITEM wineItem)
2001 {
2002     TREEVIEW_ITEM *retval;
2003
2004     retval = 0;
2005
2006     /* handle all the global data here */
2007     switch (which)
2008     {
2009     case TVGN_CHILD:            /* Special case: child of 0 is root */
2010         if (wineItem)
2011             break;
2012         /* fall through */
2013     case TVGN_ROOT:
2014         retval = infoPtr->root->firstChild;
2015         break;
2016
2017     case TVGN_CARET:
2018         retval = infoPtr->selectedItem;
2019         break;
2020
2021     case TVGN_FIRSTVISIBLE:
2022         retval = infoPtr->firstVisible;
2023         break;
2024
2025     case TVGN_DROPHILITE:
2026         retval = infoPtr->dropItem;
2027         break;
2028
2029     case TVGN_LASTVISIBLE:
2030         retval = TREEVIEW_GetLastListItem(infoPtr, infoPtr->root);
2031         break;
2032     }
2033
2034     if (retval)
2035     {
2036         TRACE("flags:%x, returns %p\n", which, retval);
2037         return (LRESULT)retval;
2038     }
2039
2040     if (!TREEVIEW_ValidItem(infoPtr, wineItem))
2041         return FALSE;
2042
2043     switch (which)
2044     {
2045     case TVGN_NEXT:
2046         retval = wineItem->nextSibling;
2047         break;
2048     case TVGN_PREVIOUS:
2049         retval = wineItem->prevSibling;
2050         break;
2051     case TVGN_PARENT:
2052         retval = (wineItem->parent != infoPtr->root) ? wineItem->parent : NULL;
2053         break;
2054     case TVGN_CHILD:
2055         retval = wineItem->firstChild;
2056         break;
2057     case TVGN_NEXTVISIBLE:
2058         retval = TREEVIEW_GetNextListItem(infoPtr, wineItem);
2059         break;
2060     case TVGN_PREVIOUSVISIBLE:
2061         retval = TREEVIEW_GetPrevListItem(infoPtr, wineItem);
2062         break;
2063     default:
2064         TRACE("Unknown msg %x,item %p\n", which, wineItem);
2065         break;
2066     }
2067
2068     TRACE("flags:%x, item %p;returns %p\n", which, wineItem, retval);
2069     return (LRESULT)retval;
2070 }
2071
2072
2073 static LRESULT
2074 TREEVIEW_GetCount(TREEVIEW_INFO *infoPtr)
2075 {
2076     TRACE(" %d\n", infoPtr->uNumItems);
2077     return (LRESULT)infoPtr->uNumItems;
2078 }
2079
2080 static VOID
2081 TREEVIEW_ToggleItemState(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *item)
2082 {
2083     if (infoPtr->dwStyle & TVS_CHECKBOXES)
2084     {
2085         static const unsigned int state_table[] = { 0, 2, 1 };
2086
2087         unsigned int state;
2088
2089         state = STATEIMAGEINDEX(item->state);
2090         TRACE("state:%x\n", state);
2091         item->state &= ~TVIS_STATEIMAGEMASK;
2092
2093         if (state < 3)
2094             state = state_table[state];
2095
2096         item->state |= INDEXTOSTATEIMAGEMASK(state);
2097
2098         TRACE("state:%x\n", state);
2099         TREEVIEW_Invalidate(infoPtr, item);
2100     }
2101 }
2102
2103
2104 /* Painting *************************************************************/
2105
2106 /* Draw the lines and expand button for an item. Also draws one section
2107  * of the line from item's parent to item's parent's next sibling. */
2108 static void
2109 TREEVIEW_DrawItemLines(TREEVIEW_INFO *infoPtr, HDC hdc, TREEVIEW_ITEM *item)
2110 {
2111     LONG centerx, centery;
2112     BOOL lar = ((infoPtr->dwStyle
2113                  & (TVS_LINESATROOT|TVS_HASLINES|TVS_HASBUTTONS))
2114                 > TVS_LINESATROOT);
2115
2116     if (!lar && item->iLevel == 0)
2117         return;
2118
2119     centerx = (item->linesOffset + item->stateOffset) / 2;
2120     centery = (item->rect.top + item->rect.bottom) / 2;
2121
2122     if (infoPtr->dwStyle & TVS_HASLINES)
2123     {
2124         HPEN hOldPen, hNewPen;
2125         HTREEITEM parent;
2126
2127         /* 
2128          * Get a dotted grey pen
2129          */
2130         hNewPen = CreatePen(PS_ALTERNATE, 0, infoPtr->clrLine);
2131         hOldPen = SelectObject(hdc, hNewPen);
2132
2133         MoveToEx(hdc, item->stateOffset, centery, NULL);
2134         LineTo(hdc, centerx - 1, centery);
2135
2136         if (item->prevSibling || item->parent != infoPtr->root)
2137         {
2138             MoveToEx(hdc, centerx, item->rect.top, NULL);
2139             LineTo(hdc, centerx, centery);
2140         }
2141
2142         if (item->nextSibling)
2143         {
2144             MoveToEx(hdc, centerx, centery, NULL);
2145             LineTo(hdc, centerx, item->rect.bottom + 1);
2146         }
2147
2148         /* Draw the line from our parent to its next sibling. */
2149         parent = item->parent;
2150         while (parent != infoPtr->root)
2151         {
2152             int pcenterx = (parent->linesOffset + parent->stateOffset) / 2;
2153
2154             if (parent->nextSibling
2155                 /* skip top-levels unless TVS_LINESATROOT */
2156                 && parent->stateOffset > parent->linesOffset)
2157             {
2158                 MoveToEx(hdc, pcenterx, item->rect.top, NULL);
2159                 LineTo(hdc, pcenterx, item->rect.bottom + 1);
2160             }
2161
2162             parent = parent->parent;
2163         }
2164
2165         SelectObject(hdc, hOldPen);
2166         DeleteObject(hNewPen);
2167     }
2168
2169     /* 
2170      * Display the (+/-) signs
2171      */
2172
2173     if (infoPtr->dwStyle & TVS_HASBUTTONS)
2174     {
2175         if (item->cChildren)
2176         {
2177             LONG height = item->rect.bottom - item->rect.top;
2178             LONG width  = item->stateOffset - item->linesOffset;
2179             LONG rectsize = min(height, width) / 4;
2180             /* plussize = ceil(rectsize * 3/4) */
2181             LONG plussize = (rectsize + 1) * 3 / 4;
2182
2183             HPEN hNewPen  = CreatePen(PS_SOLID, 0, infoPtr->clrLine);
2184             HPEN hOldPen  = SelectObject(hdc, hNewPen);
2185             HBRUSH hbr    = CreateSolidBrush(infoPtr->clrBk);
2186             HBRUSH hbrOld = SelectObject(hdc, hbr);
2187
2188             Rectangle(hdc, centerx - rectsize, centery - rectsize,
2189                       centerx + rectsize + 1, centery + rectsize + 1);
2190
2191             SelectObject(hdc, hbrOld);
2192             DeleteObject(hbr);
2193
2194             SelectObject(hdc, hOldPen);
2195             DeleteObject(hNewPen);
2196
2197             MoveToEx(hdc, centerx - plussize + 1, centery, NULL);
2198             LineTo(hdc, centerx + plussize, centery);
2199
2200             if (!(item->state & TVIS_EXPANDED))
2201             {
2202                 MoveToEx(hdc, centerx, centery - plussize + 1, NULL);
2203                 LineTo(hdc, centerx, centery + plussize);
2204             }
2205         }
2206     }
2207 }
2208
2209 static void
2210 TREEVIEW_DrawItem(TREEVIEW_INFO *infoPtr, HDC hdc, TREEVIEW_ITEM *wineItem)
2211 {
2212     INT cditem;
2213     HFONT hOldFont;
2214     int centery;
2215
2216     hOldFont = SelectObject(hdc, TREEVIEW_FontForItem(infoPtr, wineItem));
2217
2218     TREEVIEW_UpdateDispInfo(infoPtr, wineItem, CALLBACK_MASK_ALL);
2219
2220     /* The custom draw handler can query the text rectangle,
2221      * so get ready. */
2222     TREEVIEW_ComputeTextWidth(infoPtr, wineItem, hdc);
2223
2224     cditem = 0;
2225
2226     if (infoPtr->cdmode & CDRF_NOTIFYITEMDRAW)
2227     {
2228         cditem = TREEVIEW_SendCustomDrawItemNotify
2229             (infoPtr, hdc, wineItem, CDDS_ITEMPREPAINT);
2230         TRACE("prepaint:cditem-app returns 0x%x\n", cditem);
2231
2232         if (cditem & CDRF_SKIPDEFAULT)
2233         {
2234             SelectObject(hdc, hOldFont);
2235             return;
2236         }
2237     }
2238
2239     if (cditem & CDRF_NEWFONT)
2240         TREEVIEW_ComputeTextWidth(infoPtr, wineItem, hdc);
2241
2242     TREEVIEW_DrawItemLines(infoPtr, hdc, wineItem);
2243
2244     centery = (wineItem->rect.top + wineItem->rect.bottom) / 2;
2245
2246     /* 
2247      * Display the images associated with this item
2248      */
2249     {
2250         INT imageIndex;
2251
2252         /* State images are displayed to the left of the Normal image
2253          * image number is in state; zero should be `display no image'.
2254          */
2255         imageIndex = STATEIMAGEINDEX(wineItem->state);
2256
2257         if (infoPtr->himlState && imageIndex)
2258         {
2259             ImageList_Draw(infoPtr->himlState, imageIndex, hdc,
2260                            wineItem->stateOffset,
2261                            centery - infoPtr->stateImageHeight / 2,
2262                            ILD_NORMAL);
2263         }
2264
2265         /* Now, draw the normal image; can be either selected or
2266          * non-selected image. 
2267          */
2268
2269         if ((wineItem->state & TVIS_SELECTED) && (wineItem->iSelectedImage))
2270         {
2271             /* The item is curently selected */
2272             imageIndex = wineItem->iSelectedImage;
2273         }
2274         else
2275         {
2276             /* The item is not selected */
2277             imageIndex = wineItem->iImage;
2278         }
2279
2280         if (infoPtr->himlNormal)
2281         {
2282             int ovlIdx = wineItem->state & TVIS_OVERLAYMASK;
2283
2284             ImageList_Draw(infoPtr->himlNormal, imageIndex, hdc,
2285                            wineItem->imageOffset,
2286                            centery - infoPtr->normalImageHeight / 2,
2287                            ILD_NORMAL | ovlIdx);
2288         }
2289     }
2290
2291
2292     /* 
2293      * Display the text associated with this item
2294      */
2295
2296     /* Don't paint item's text if it's being edited */
2297     if (!infoPtr->hwndEdit || (infoPtr->selectedItem != wineItem))
2298     {
2299         if (wineItem->pszText)
2300         {
2301             COLORREF oldTextColor = 0;
2302             INT oldBkMode;
2303             HBRUSH hbrBk = 0;
2304             BOOL inFocus = (GetFocus() == infoPtr->hwnd);
2305             RECT rcText;
2306
2307             oldBkMode = SetBkMode(hdc, TRANSPARENT);
2308
2309             /* - If item is drop target or it is selected and window is in focus -
2310              * use blue background (COLOR_HIGHLIGHT).
2311              * - If item is selected, window is not in focus, but it has style
2312              * TVS_SHOWSELALWAYS - use grey background (COLOR_BTNFACE)
2313              * - Otherwise - don't fill background
2314              */
2315             if ((wineItem->state & TVIS_DROPHILITED) || ((wineItem == infoPtr->focusedItem) && !(wineItem->state & TVIS_SELECTED)) ||
2316                 ((wineItem->state & TVIS_SELECTED) && (!infoPtr->focusedItem) &&
2317                  (inFocus || (infoPtr->dwStyle & TVS_SHOWSELALWAYS))))
2318             {
2319                 if ((wineItem->state & TVIS_DROPHILITED) || inFocus)
2320                 {
2321                     hbrBk = CreateSolidBrush(GetSysColor(COLOR_HIGHLIGHT));
2322                     oldTextColor =
2323                         SetTextColor(hdc, GetSysColor(COLOR_HIGHLIGHTTEXT));
2324                 }
2325                 else
2326                 {
2327                     hbrBk = CreateSolidBrush(GetSysColor(COLOR_BTNFACE));
2328
2329                     if (infoPtr->clrText == -1)
2330                         oldTextColor =
2331                             SetTextColor(hdc, GetSysColor(COLOR_WINDOWTEXT));
2332                     else
2333                         oldTextColor = SetTextColor(hdc, infoPtr->clrText);
2334                 }
2335             }
2336             else
2337             {
2338                 if (infoPtr->clrText == -1)
2339                     oldTextColor =
2340                         SetTextColor(hdc, GetSysColor(COLOR_WINDOWTEXT));
2341                 else
2342                     oldTextColor = SetTextColor(hdc, infoPtr->clrText);
2343             }
2344
2345             rcText.top = wineItem->rect.top;
2346             rcText.bottom = wineItem->rect.bottom;
2347             rcText.left = wineItem->textOffset;
2348             rcText.right = rcText.left + wineItem->textWidth + 4;
2349
2350             if (hbrBk)
2351             {
2352                 FillRect(hdc, &rcText, hbrBk);
2353                 DeleteObject(hbrBk);
2354             }
2355
2356             /* Draw the box around the selected item */
2357             if ((wineItem == infoPtr->selectedItem) && inFocus)
2358             {
2359                 DrawFocusRect(hdc,&rcText);
2360             }
2361
2362             InflateRect(&rcText, -2, -1); /* allow for the focus rect */
2363
2364             /* Draw it */
2365             DrawTextA(hdc,
2366                       wineItem->pszText,
2367                       lstrlenA(wineItem->pszText),
2368                       &rcText,
2369                       DT_CENTER | DT_VCENTER | DT_SINGLELINE | DT_NOPREFIX);
2370
2371             /* Restore the hdc state */
2372             SetTextColor(hdc, oldTextColor);
2373
2374             if (oldBkMode != TRANSPARENT)
2375                 SetBkMode(hdc, oldBkMode);
2376         }
2377     }
2378
2379     /* Draw insertion mark if necessary */
2380
2381     if (infoPtr->insertMarkItem)
2382         TRACE("item:%d,mark:%d\n",
2383               TREEVIEW_GetItemIndex(infoPtr, wineItem),
2384               (int)infoPtr->insertMarkItem);
2385
2386     if (wineItem == infoPtr->insertMarkItem)
2387     {
2388         HPEN hNewPen, hOldPen;
2389         int offset;
2390         int left, right;
2391
2392         hNewPen = CreatePen(PS_SOLID, 2, infoPtr->clrInsertMark);
2393         hOldPen = SelectObject(hdc, hNewPen);
2394
2395         if (infoPtr->insertBeforeorAfter)
2396             offset = wineItem->rect.bottom - 1;
2397         else
2398             offset = wineItem->rect.top + 1;
2399
2400         left = wineItem->textOffset - 2;
2401         right = wineItem->textOffset + wineItem->textWidth + 2;
2402
2403         MoveToEx(hdc, left, offset - 3, NULL);
2404         LineTo(hdc, left, offset + 4);
2405
2406         MoveToEx(hdc, left, offset, NULL);
2407         LineTo(hdc, right + 1, offset);
2408
2409         MoveToEx(hdc, right, offset + 3, NULL);
2410         LineTo(hdc, right, offset - 4);
2411
2412         SelectObject(hdc, hOldPen);
2413         DeleteObject(hNewPen);
2414     }
2415
2416     if (cditem & CDRF_NOTIFYPOSTPAINT)
2417     {
2418         cditem = TREEVIEW_SendCustomDrawItemNotify
2419             (infoPtr, hdc, wineItem, CDDS_ITEMPOSTPAINT);
2420         TRACE("postpaint:cditem-app returns 0x%x\n", cditem);
2421     }
2422
2423     SelectObject(hdc, hOldFont);
2424 }
2425
2426 /* Computes treeHeight and treeWidth and updates the scroll bars.
2427  */
2428 static void
2429 TREEVIEW_UpdateScrollBars(TREEVIEW_INFO *infoPtr)
2430 {
2431     TREEVIEW_ITEM *wineItem;
2432     HWND hwnd = infoPtr->hwnd;
2433     BOOL vert = FALSE;
2434     BOOL horz = FALSE;
2435     SCROLLINFO si;
2436     LONG scrollX = infoPtr->scrollX;
2437
2438     infoPtr->treeWidth = 0;
2439     infoPtr->treeHeight = 0;
2440
2441     /* We iterate through all visible items in order to get the tree height
2442      * and width */
2443     wineItem = infoPtr->root->firstChild;
2444
2445     while (wineItem != NULL)
2446     {
2447         if (ISVISIBLE(wineItem))
2448         {
2449             /* actually we draw text at textOffset + 2 */
2450             if (2+wineItem->textOffset+wineItem->textWidth > infoPtr->treeWidth)
2451                 infoPtr->treeWidth = wineItem->textOffset+wineItem->textWidth+2;
2452
2453             /* This is scroll-adjusted, but we fix this below. */
2454             infoPtr->treeHeight = wineItem->rect.bottom;
2455         }
2456
2457         wineItem = TREEVIEW_GetNextListItem(infoPtr, wineItem);
2458     }
2459
2460     /* Fix the scroll adjusted treeHeight and treeWidth. */
2461     if (infoPtr->root->firstChild)
2462         infoPtr->treeHeight -= infoPtr->root->firstChild->rect.top;
2463
2464     infoPtr->treeWidth += infoPtr->scrollX;
2465
2466     /* Adding one scroll bar may take up enough space that it forces us
2467      * to add the other as well. */
2468     if (infoPtr->treeHeight > infoPtr->clientHeight)
2469     {
2470         vert = TRUE;
2471
2472         if (infoPtr->treeWidth
2473             > infoPtr->clientWidth - GetSystemMetrics(SM_CXVSCROLL))
2474             horz = TRUE;
2475     }
2476     else if (infoPtr->treeWidth > infoPtr->clientWidth)
2477         horz = TRUE;
2478
2479     if (!vert && horz && infoPtr->treeHeight
2480         > infoPtr->clientHeight - GetSystemMetrics(SM_CYVSCROLL))
2481         vert = TRUE;
2482
2483     si.cbSize = sizeof(SCROLLINFO);
2484     si.fMask  = SIF_POS|SIF_RANGE|SIF_PAGE;
2485     si.nMin   = 0;
2486
2487     if (vert)
2488     {
2489         si.nPage = TREEVIEW_GetVisibleCount(infoPtr);
2490         si.nPos  = infoPtr->firstVisible->visibleOrder;
2491         si.nMax  = infoPtr->maxVisibleOrder - 1;
2492
2493         SetScrollInfo(hwnd, SB_VERT, &si, TRUE);
2494
2495         if (!(infoPtr->uInternalStatus & TV_VSCROLL))
2496             ShowScrollBar(hwnd, SB_VERT, TRUE);
2497         infoPtr->uInternalStatus |= TV_VSCROLL;
2498     }
2499     else
2500     {
2501         if (infoPtr->uInternalStatus & TV_VSCROLL)
2502             ShowScrollBar(hwnd, SB_VERT, FALSE);
2503         infoPtr->uInternalStatus &= ~TV_VSCROLL;
2504     }
2505
2506     if (horz)
2507     {
2508         si.nPage = infoPtr->clientWidth;
2509         si.nPos  = infoPtr->scrollX;
2510         si.nMax  = infoPtr->treeWidth - 1;
2511
2512         if (si.nPos > si.nMax - max( si.nPage-1, 0 ))
2513         {
2514            si.nPos = si.nMax - max( si.nPage-1, 0 );
2515            scrollX = si.nPos;
2516         }
2517
2518         if (!(infoPtr->uInternalStatus & TV_HSCROLL))
2519             ShowScrollBar(hwnd, SB_HORZ, TRUE);
2520         infoPtr->uInternalStatus |= TV_HSCROLL;
2521
2522         SetScrollInfo(hwnd, SB_HORZ, &si, TRUE);
2523     }
2524     else
2525     {
2526         if (infoPtr->uInternalStatus & TV_HSCROLL)
2527             ShowScrollBar(hwnd, SB_HORZ, FALSE);
2528         infoPtr->uInternalStatus &= ~TV_HSCROLL;
2529
2530         scrollX = 0;
2531     }
2532
2533     if (infoPtr->scrollX != scrollX)
2534     {
2535         TREEVIEW_HScroll(infoPtr,
2536                          MAKEWPARAM(SB_THUMBPOSITION, scrollX));
2537     }
2538
2539     if (!horz)
2540         infoPtr->uInternalStatus &= ~TV_HSCROLL;
2541 }
2542
2543 /* CtrlSpy doesn't mention this, but CorelDRAW's object manager needs it. */
2544 static LRESULT
2545 TREEVIEW_EraseBackground(TREEVIEW_INFO *infoPtr, HDC hDC)
2546 {
2547     HBRUSH hBrush = CreateSolidBrush(infoPtr->clrBk);
2548     RECT rect;
2549
2550     GetClientRect(infoPtr->hwnd, &rect);
2551     FillRect(hDC, &rect, hBrush);
2552     DeleteObject(hBrush);
2553
2554     return 1;
2555 }
2556
2557 static void
2558 TREEVIEW_Refresh(TREEVIEW_INFO *infoPtr, HDC hdc, RECT *rc)
2559 {
2560     HWND hwnd = infoPtr->hwnd;
2561     RECT rect = *rc;
2562     TREEVIEW_ITEM *wineItem;
2563
2564     if (infoPtr->clientHeight == 0 || infoPtr->clientWidth == 0)
2565     {
2566         TRACE("empty window\n");
2567         return;
2568     }
2569
2570     infoPtr->cdmode = TREEVIEW_SendCustomDrawNotify(infoPtr, CDDS_PREPAINT,
2571                                                     hdc, rect);
2572
2573     if (infoPtr->cdmode == CDRF_SKIPDEFAULT)
2574     {
2575         ReleaseDC(hwnd, hdc);
2576         return;
2577     }
2578
2579     for (wineItem = infoPtr->root->firstChild;
2580          wineItem != NULL;
2581          wineItem = TREEVIEW_GetNextListItem(infoPtr, wineItem))
2582     {
2583         if (ISVISIBLE(wineItem))
2584         {
2585             /* Avoid unneeded calculations */
2586             if (wineItem->rect.top > rect.bottom)
2587                 break;
2588             if (wineItem->rect.bottom < rect.top)
2589                 continue;
2590
2591             TREEVIEW_DrawItem(infoPtr, hdc, wineItem);
2592         }
2593     }
2594
2595     TREEVIEW_UpdateScrollBars(infoPtr);
2596
2597     if (infoPtr->cdmode & CDRF_NOTIFYPOSTPAINT)
2598         infoPtr->cdmode =
2599             TREEVIEW_SendCustomDrawNotify(infoPtr, CDDS_POSTPAINT, hdc, rect);
2600 }
2601
2602 static void
2603 TREEVIEW_Invalidate(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *item)
2604 {
2605     if (item != NULL)
2606         InvalidateRect(infoPtr->hwnd, &item->rect, TRUE);
2607     else
2608         InvalidateRect(infoPtr->hwnd, NULL, TRUE);
2609 }
2610
2611 static LRESULT
2612 TREEVIEW_Paint(TREEVIEW_INFO *infoPtr, WPARAM wParam)
2613 {
2614     HDC hdc;
2615     PAINTSTRUCT ps;
2616     RECT rc;
2617
2618     TRACE("\n");
2619
2620     if (wParam)
2621     {
2622         hdc = (HDC)wParam;
2623         if (!GetUpdateRect(infoPtr->hwnd, &rc, TRUE))
2624         {
2625             HBITMAP hbitmap;
2626             BITMAP bitmap;
2627             hbitmap = GetCurrentObject(hdc, OBJ_BITMAP);
2628             if (!hbitmap) return 0;
2629             GetObjectA(hbitmap, sizeof(BITMAP), &bitmap);
2630             rc.left = 0; rc.top = 0;
2631             rc.right = bitmap.bmWidth;
2632             rc.bottom = bitmap.bmHeight;  
2633             TREEVIEW_EraseBackground(infoPtr, wParam);
2634         }
2635     }
2636     else
2637     {
2638         hdc = BeginPaint(infoPtr->hwnd, &ps);
2639         rc = ps.rcPaint;
2640     }
2641
2642     if(infoPtr->bRedraw) /* WM_SETREDRAW sets bRedraw */
2643         TREEVIEW_Refresh(infoPtr, hdc, &rc);
2644
2645     if (!wParam)
2646         EndPaint(infoPtr->hwnd, &ps);
2647
2648     return 0;
2649 }
2650
2651
2652 /* Sorting **************************************************************/
2653
2654 /***************************************************************************
2655  * Forward the DPA local callback to the treeview owner callback
2656  */
2657 static INT WINAPI
2658 TREEVIEW_CallBackCompare(TREEVIEW_ITEM *first, TREEVIEW_ITEM *second, LPTVSORTCB pCallBackSort)
2659 {
2660     /* Forward the call to the client-defined callback */
2661     return pCallBackSort->lpfnCompare(first->lParam,
2662                                       second->lParam,
2663                                       pCallBackSort->lParam);
2664 }
2665
2666 /***************************************************************************
2667  * Treeview native sort routine: sort on item text.
2668  */
2669 static INT WINAPI
2670 TREEVIEW_SortOnName(TREEVIEW_ITEM *first, TREEVIEW_ITEM *second,
2671                      TREEVIEW_INFO *infoPtr)
2672 {
2673     TREEVIEW_UpdateDispInfo(infoPtr, first, TVIF_TEXT);
2674     TREEVIEW_UpdateDispInfo(infoPtr, second, TVIF_TEXT);
2675
2676     return strcasecmp(first->pszText, second->pszText);
2677 }
2678
2679 /* Returns the number of physical children belonging to item. */
2680 static INT
2681 TREEVIEW_CountChildren(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *item)
2682 {
2683     INT cChildren = 0;
2684     HTREEITEM hti;
2685
2686     for (hti = item->firstChild; hti != NULL; hti = hti->nextSibling)
2687         cChildren++;
2688
2689     return cChildren;
2690 }
2691
2692 /* Returns a DPA containing a pointer to each physical child of item in
2693  * sibling order. If item has no children, an empty DPA is returned. */
2694 static HDPA
2695 TREEVIEW_BuildChildDPA(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *item)
2696 {
2697     HTREEITEM child = item->firstChild;
2698
2699     HDPA list = DPA_Create(8);
2700     if (list == 0) return NULL;
2701
2702     for (child = item->firstChild; child != NULL; child = child->nextSibling)
2703     {
2704         if (DPA_InsertPtr(list, INT_MAX, child) == -1)
2705         {
2706             DPA_Destroy(list);
2707             return NULL;
2708         }
2709     }
2710
2711     return list;
2712 }
2713
2714 /***************************************************************************
2715  * Setup the treeview structure with regards of the sort method
2716  * and sort the children of the TV item specified in lParam
2717  * fRecurse: currently unused. Should be zero.
2718  * parent: if pSort!=NULL, should equal pSort->hParent.
2719  *         otherwise, item which child items are to be sorted.
2720  * pSort:  sort method info. if NULL, sort on item text.
2721  *         if non-NULL, sort on item's lParam content, and let the
2722  *         application decide what that means. See also TVM_SORTCHILDRENCB.
2723  */
2724
2725 static LRESULT
2726 TREEVIEW_Sort(TREEVIEW_INFO *infoPtr, BOOL fRecurse, HTREEITEM parent,
2727               LPTVSORTCB pSort)
2728 {
2729     INT cChildren;
2730     PFNDPACOMPARE pfnCompare;
2731     LPARAM lpCompare;
2732
2733     /* undocumented feature: TVI_ROOT means `sort the whole tree' */
2734     if (parent == TVI_ROOT)
2735         parent = infoPtr->root;
2736
2737     /* Check for a valid handle to the parent item */
2738     if (!TREEVIEW_ValidItem(infoPtr, parent))
2739     {
2740         ERR("invalid item hParent=%x\n", (INT)parent);
2741         return FALSE;
2742     }
2743
2744     if (pSort)
2745     {
2746         pfnCompare = (PFNDPACOMPARE)TREEVIEW_CallBackCompare;
2747         lpCompare = (LPARAM)pSort;
2748     }
2749     else
2750     {
2751         pfnCompare = (PFNDPACOMPARE)TREEVIEW_SortOnName;
2752         lpCompare = (LPARAM)infoPtr;
2753     }
2754
2755     cChildren = TREEVIEW_CountChildren(infoPtr, parent);
2756
2757     /* Make sure there is something to sort */
2758     if (cChildren > 1)
2759     {
2760         /* TREEVIEW_ITEM rechaining */
2761         INT count = 0;
2762         HTREEITEM item = 0;
2763         HTREEITEM nextItem = 0;
2764         HTREEITEM prevItem = 0;
2765
2766         HDPA sortList = TREEVIEW_BuildChildDPA(infoPtr, parent);
2767
2768         if (sortList == NULL)
2769             return FALSE;
2770
2771         /* let DPA sort the list */
2772         DPA_Sort(sortList, pfnCompare, lpCompare);
2773
2774         /* The order of DPA entries has been changed, so fixup the
2775          * nextSibling and prevSibling pointers. */
2776
2777         item = (HTREEITEM)DPA_GetPtr(sortList, count++);
2778         while ((nextItem = (HTREEITEM)DPA_GetPtr(sortList, count++)) != NULL)
2779         {
2780             /* link the two current item toghether */
2781             item->nextSibling = nextItem;
2782             nextItem->prevSibling = item;
2783
2784             if (prevItem == NULL)
2785             {
2786                 /* this is the first item, update the parent */
2787                 parent->firstChild = item;
2788                 item->prevSibling = NULL;
2789             }
2790             else
2791             {
2792                 /* fix the back chaining */
2793                 item->prevSibling = prevItem;
2794             }
2795
2796             /* get ready for the next one */
2797             prevItem = item;
2798             item = nextItem;
2799         }
2800
2801         /* the last item is pointed to by item and never has a sibling */
2802         item->nextSibling = NULL;
2803         parent->lastChild = item;
2804
2805         DPA_Destroy(sortList);
2806
2807         TREEVIEW_VerifyTree(infoPtr);
2808
2809         if (parent->state & TVIS_EXPANDED)
2810         {
2811             int visOrder = infoPtr->firstVisible->visibleOrder;
2812
2813         if (parent == infoPtr->root)
2814             TREEVIEW_RecalculateVisibleOrder(infoPtr, NULL);
2815         else
2816             TREEVIEW_RecalculateVisibleOrder(infoPtr, parent);
2817
2818             if (TREEVIEW_IsChildOf(parent, infoPtr->firstVisible))
2819             {
2820                 TREEVIEW_ITEM *item;
2821
2822                 for (item = infoPtr->root->firstChild; item != NULL;
2823                      item = TREEVIEW_GetNextListItem(infoPtr, item))
2824                 {
2825                     if (item->visibleOrder == visOrder)
2826                         break;
2827                 }
2828
2829                 TREEVIEW_SetFirstVisible(infoPtr, item, FALSE);
2830             }
2831
2832             TREEVIEW_Invalidate(infoPtr, NULL);
2833         }
2834
2835         return TRUE;
2836     }
2837     return FALSE;
2838 }
2839
2840
2841 /***************************************************************************
2842  * Setup the treeview structure with regards of the sort method
2843  * and sort the children of the TV item specified in lParam
2844  */
2845 static LRESULT
2846 TREEVIEW_SortChildrenCB(TREEVIEW_INFO *infoPtr, WPARAM wParam, LPTVSORTCB pSort)
2847 {
2848     return TREEVIEW_Sort(infoPtr, wParam, pSort->hParent, pSort);
2849 }
2850
2851
2852 /***************************************************************************
2853  * Sort the children of the TV item specified in lParam.
2854  */
2855 static LRESULT
2856 TREEVIEW_SortChildren(TREEVIEW_INFO *infoPtr, WPARAM wParam, LPARAM lParam)
2857 {
2858     return TREEVIEW_Sort(infoPtr, (BOOL)wParam, (HTREEITEM)lParam, NULL);
2859 }
2860
2861
2862 /* Expansion/Collapse ***************************************************/
2863
2864 static BOOL
2865 TREEVIEW_SendExpanding(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *wineItem,
2866                        UINT action)
2867 {
2868     return !TREEVIEW_SendTreeviewNotify(infoPtr, TVN_ITEMEXPANDINGA, action,
2869                                         TVIF_HANDLE | TVIF_STATE | TVIF_PARAM
2870                                         | TVIF_IMAGE | TVIF_SELECTEDIMAGE,
2871                                         0, wineItem);
2872 }
2873
2874 static VOID
2875 TREEVIEW_SendExpanded(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *wineItem,
2876                       UINT action)
2877 {
2878     TREEVIEW_SendTreeviewNotify(infoPtr, TVN_ITEMEXPANDEDA, action,
2879                                 TVIF_HANDLE | TVIF_STATE | TVIF_PARAM
2880                                 | TVIF_IMAGE | TVIF_SELECTEDIMAGE,
2881                                 0, wineItem);
2882 }
2883
2884
2885 /* This corresponds to TVM_EXPAND with TVE_COLLAPSE.
2886  * bRemoveChildren corresponds to TVE_COLLAPSERESET. */
2887 static BOOL
2888 TREEVIEW_Collapse(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *wineItem,
2889                   BOOL bRemoveChildren, BOOL bUser)
2890 {
2891     UINT action = TVE_COLLAPSE | (bRemoveChildren ? TVE_COLLAPSERESET : 0);
2892     BOOL bSetSelection, bSetFirstVisible;
2893
2894     TRACE("TVE_COLLAPSE %p %s\n", wineItem, TREEVIEW_ItemName(wineItem));
2895
2896     if (!(wineItem->state & TVIS_EXPANDED) || wineItem->firstChild == NULL)
2897         return FALSE;
2898
2899     if (bUser)
2900         TREEVIEW_SendExpanding(infoPtr, wineItem, action);
2901
2902     wineItem->state &= ~TVIS_EXPANDED;
2903
2904     if (bUser)
2905         TREEVIEW_SendExpanded(infoPtr, wineItem, action);
2906
2907     bSetSelection = (infoPtr->selectedItem != NULL
2908                      && TREEVIEW_IsChildOf(wineItem, infoPtr->selectedItem));
2909
2910     bSetFirstVisible = (infoPtr->firstVisible != NULL
2911                         && TREEVIEW_IsChildOf(wineItem, infoPtr->firstVisible));
2912
2913     if (bRemoveChildren)
2914     {
2915         TRACE("TVE_COLLAPSERESET\n");
2916         wineItem->state &= ~TVIS_EXPANDEDONCE;
2917         TREEVIEW_RemoveAllChildren(infoPtr, wineItem);
2918     }
2919
2920     if (wineItem->firstChild)
2921     {
2922         TREEVIEW_ITEM *item, *sibling;
2923
2924         sibling = TREEVIEW_GetNextListItem(infoPtr, wineItem);
2925
2926         for (item = wineItem->firstChild; item != sibling;
2927              item = TREEVIEW_GetNextListItem(infoPtr, item))
2928         {
2929             item->visibleOrder = -1;
2930         }
2931     }
2932
2933     TREEVIEW_RecalculateVisibleOrder(infoPtr, wineItem);
2934
2935     TREEVIEW_SetFirstVisible(infoPtr, bSetFirstVisible ? wineItem
2936                              : infoPtr->firstVisible, TRUE);
2937
2938     if (bSetSelection)
2939     {
2940         /* Don't call DoSelectItem, it sends notifications. */
2941         if (TREEVIEW_ValidItem(infoPtr, infoPtr->selectedItem))
2942             infoPtr->selectedItem->state &= ~TVIS_SELECTED;
2943         wineItem->state |= TVIS_SELECTED;
2944         infoPtr->selectedItem = wineItem;
2945
2946         TREEVIEW_EnsureVisible(infoPtr, wineItem, FALSE);
2947     }
2948
2949     TREEVIEW_UpdateScrollBars(infoPtr);
2950     TREEVIEW_Invalidate(infoPtr, NULL);
2951
2952     return TRUE;
2953 }
2954
2955 static BOOL
2956 TREEVIEW_Expand(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *wineItem,
2957                 BOOL bExpandPartial, BOOL bUser)
2958 {
2959     TRACE("\n");
2960
2961     if (!TREEVIEW_HasChildren(infoPtr, wineItem)
2962         || wineItem->state & TVIS_EXPANDED)
2963         return FALSE;
2964
2965     TRACE("TVE_EXPAND %p %s\n", wineItem, TREEVIEW_ItemName(wineItem));
2966
2967     if (bUser || !(wineItem->state & TVIS_EXPANDEDONCE))
2968     {
2969         if (!TREEVIEW_SendExpanding(infoPtr, wineItem, TVE_EXPAND))
2970         {
2971             TRACE("  TVN_ITEMEXPANDING returned TRUE, exiting...\n");
2972             return FALSE;
2973         }
2974
2975         wineItem->state |= TVIS_EXPANDED;
2976         TREEVIEW_SendExpanded(infoPtr, wineItem, TVE_EXPAND);
2977         wineItem->state |= TVIS_EXPANDEDONCE;
2978     }
2979     else
2980     {
2981         /* this item has already been expanded */
2982         wineItem->state |= TVIS_EXPANDED;
2983     }
2984
2985     if (bExpandPartial)
2986         FIXME("TVE_EXPANDPARTIAL not implemented\n");
2987
2988     TREEVIEW_RecalculateVisibleOrder(infoPtr, wineItem);
2989     TREEVIEW_UpdateSubTree(infoPtr, wineItem);
2990     TREEVIEW_UpdateScrollBars(infoPtr);
2991
2992     /* Scroll up so that as many children as possible are visible.
2993      * This looses when expanding causes an HScroll bar to appear, but we
2994      * don't know that yet, so the last item is obscured. */
2995     if (wineItem->firstChild != NULL)
2996     {
2997         int nChildren = wineItem->lastChild->visibleOrder
2998             - wineItem->firstChild->visibleOrder + 1;
2999
3000         int visible_pos = wineItem->visibleOrder
3001             - infoPtr->firstVisible->visibleOrder;
3002
3003         int rows_below = TREEVIEW_GetVisibleCount(infoPtr) - visible_pos - 1;
3004
3005         if (visible_pos > 0 && nChildren > rows_below)
3006         {
3007             int scroll = nChildren - rows_below;
3008
3009             if (scroll > visible_pos)
3010                 scroll = visible_pos;
3011
3012             if (scroll > 0)
3013             {
3014                 TREEVIEW_ITEM *newFirstVisible
3015                     = TREEVIEW_GetListItem(infoPtr, infoPtr->firstVisible,
3016                                            scroll);
3017
3018
3019                 TREEVIEW_SetFirstVisible(infoPtr, newFirstVisible, TRUE);
3020             }
3021         }
3022     }
3023
3024     TREEVIEW_Invalidate(infoPtr, NULL);
3025
3026     return TRUE;
3027 }
3028
3029 static BOOL
3030 TREEVIEW_Toggle(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *wineItem, BOOL bUser)
3031 {
3032     TRACE("\n");
3033
3034     if (wineItem->state & TVIS_EXPANDED)
3035         return TREEVIEW_Collapse(infoPtr, wineItem, FALSE, bUser);
3036     else
3037         return TREEVIEW_Expand(infoPtr, wineItem, FALSE, bUser);
3038 }
3039
3040 static VOID
3041 TREEVIEW_ExpandAll(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *item)
3042 {
3043     TREEVIEW_Expand(infoPtr, item, FALSE, TRUE);
3044
3045     for (item = item->firstChild; item != NULL; item = item->nextSibling)
3046     {
3047         if (TREEVIEW_HasChildren(infoPtr, item))
3048             TREEVIEW_ExpandAll(infoPtr, item);
3049     }
3050 }
3051
3052 /* Note:If the specified item is the child of a collapsed parent item,
3053    the parent's list of child items is (recursively) expanded to reveal the 
3054    specified item. This is mentioned for TREEVIEW_SelectItem; don't 
3055    know if it also applies here.
3056 */
3057
3058 static LRESULT
3059 TREEVIEW_ExpandMsg(TREEVIEW_INFO *infoPtr, UINT flag, HTREEITEM wineItem)
3060 {
3061     if (!TREEVIEW_ValidItem(infoPtr, wineItem))
3062         return 0;
3063
3064     TRACE("For (%s) item:%d, flags %x, state:%d\n",
3065               TREEVIEW_ItemName(wineItem), flag,
3066               TREEVIEW_GetItemIndex(infoPtr, wineItem), wineItem->state);
3067
3068     switch (flag & TVE_TOGGLE)
3069     {
3070     case TVE_COLLAPSE:
3071         return TREEVIEW_Collapse(infoPtr, wineItem, flag & TVE_COLLAPSERESET,
3072                                  FALSE);
3073
3074     case TVE_EXPAND:
3075         return TREEVIEW_Expand(infoPtr, wineItem, flag & TVE_EXPANDPARTIAL,
3076                                FALSE);
3077
3078     case TVE_TOGGLE:
3079         return TREEVIEW_Toggle(infoPtr, wineItem, TRUE);
3080
3081     default:
3082         return 0;
3083     }
3084
3085 #if 0
3086     TRACE("Exiting, Item %p state is now %d...\n", wineItem, wineItem->state);
3087 #endif
3088 }
3089
3090 /* Hit-Testing **********************************************************/
3091
3092 static TREEVIEW_ITEM *
3093 TREEVIEW_HitTestPoint(TREEVIEW_INFO *infoPtr, POINT pt)
3094 {
3095     TREEVIEW_ITEM *wineItem;
3096     LONG row;
3097
3098     if (!infoPtr->firstVisible)
3099         return NULL;
3100
3101     row = pt.y / infoPtr->uItemHeight + infoPtr->firstVisible->visibleOrder;
3102
3103     for (wineItem = infoPtr->firstVisible; wineItem != NULL;
3104          wineItem = TREEVIEW_GetNextListItem(infoPtr, wineItem))
3105     {
3106         if (row >= wineItem->visibleOrder
3107             && row < wineItem->visibleOrder + wineItem->iIntegral)
3108             break;
3109     }
3110
3111     return wineItem;
3112 }
3113
3114 static LRESULT
3115 TREEVIEW_HitTest(TREEVIEW_INFO *infoPtr, LPTVHITTESTINFO lpht)
3116 {
3117     TREEVIEW_ITEM *wineItem;
3118     RECT rect;
3119     UINT status;
3120     LONG x, y;
3121
3122     lpht->hItem = 0;
3123     GetClientRect(infoPtr->hwnd, &rect);
3124     status = 0;
3125     x = lpht->pt.x;
3126     y = lpht->pt.y;
3127
3128     if (x < rect.left)
3129     {
3130         status |= TVHT_TOLEFT;
3131     }
3132     else if (x > rect.right)
3133     {
3134         status |= TVHT_TORIGHT;
3135     }
3136
3137     if (y < rect.top)
3138     {
3139         status |= TVHT_ABOVE;
3140     }
3141     else if (y > rect.bottom)
3142     {
3143         status |= TVHT_BELOW;
3144     }
3145
3146     if (status)
3147     {
3148         lpht->flags = status;
3149         return (LRESULT)(HTREEITEM)NULL;
3150     }
3151
3152     wineItem = TREEVIEW_HitTestPoint(infoPtr, lpht->pt);
3153     if (!wineItem)
3154     {
3155         lpht->flags = TVHT_NOWHERE;
3156         return (LRESULT)(HTREEITEM)NULL;
3157     }
3158
3159     if (x >= wineItem->textOffset + wineItem->textWidth)
3160     {
3161         lpht->flags = TVHT_ONITEMRIGHT;
3162     }
3163     else if (x >= wineItem->textOffset)
3164     {
3165         lpht->flags = TVHT_ONITEMLABEL;
3166     }
3167     else if (x >= wineItem->imageOffset)
3168     {
3169         lpht->flags = TVHT_ONITEMICON;
3170     }
3171     else if (x >= wineItem->stateOffset)
3172     {
3173         lpht->flags = TVHT_ONITEMSTATEICON;
3174     }
3175     else if (x >= wineItem->linesOffset && infoPtr->dwStyle & TVS_HASBUTTONS)
3176     {
3177         lpht->flags = TVHT_ONITEMBUTTON;
3178     }
3179     else
3180     {
3181         lpht->flags = TVHT_ONITEMINDENT;
3182     }
3183
3184     lpht->hItem = wineItem;
3185     TRACE("(%ld,%ld):result %x\n", lpht->pt.x, lpht->pt.y, lpht->flags);
3186
3187     return (LRESULT)wineItem;
3188 }
3189
3190 /* Item Label Editing ***************************************************/
3191
3192 static LRESULT
3193 TREEVIEW_GetEditControl(TREEVIEW_INFO *infoPtr)
3194 {
3195     return infoPtr->hwndEdit;
3196 }
3197
3198 static LRESULT CALLBACK
3199 TREEVIEW_Edit_SubclassProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
3200 {
3201     TREEVIEW_INFO *infoPtr;
3202     BOOL bCancel = FALSE;
3203
3204     switch (uMsg)
3205     {
3206     case WM_PAINT:
3207         {
3208             LRESULT rc;
3209             TREEVIEW_INFO *infoPtr = TREEVIEW_GetInfoPtr(GetParent(hwnd));
3210
3211             TRACE("WM_PAINT start\n");
3212             rc = CallWindowProcA(infoPtr->wpEditOrig, hwnd, uMsg, wParam,
3213                                  lParam);
3214             TRACE("WM_PAINT done\n");
3215             return rc;
3216         }
3217
3218     case WM_KILLFOCUS:
3219     {
3220         TREEVIEW_INFO *infoPtr = TREEVIEW_GetInfoPtr(GetParent(hwnd));
3221         if (infoPtr->bIgnoreEditKillFocus)
3222             return TRUE;
3223
3224         break;
3225     }
3226
3227     case WM_GETDLGCODE:
3228         return DLGC_WANTARROWS | DLGC_WANTALLKEYS;
3229
3230     case WM_KEYDOWN:
3231         if (wParam == (WPARAM)VK_ESCAPE)
3232         {
3233             bCancel = TRUE;
3234             break;
3235         }
3236         else if (wParam == (WPARAM)VK_RETURN)
3237         {
3238             break;
3239         }
3240
3241         /* fall through */
3242     default:
3243         {
3244             TREEVIEW_INFO *infoPtr = TREEVIEW_GetInfoPtr(GetParent(hwnd));
3245
3246             return CallWindowProcA(infoPtr->wpEditOrig, hwnd, uMsg, wParam,
3247                                    lParam);
3248         }
3249     }
3250
3251     /* Processing TVN_ENDLABELEDIT message could kill the focus       */
3252     /* eg. Using a messagebox                                         */
3253
3254     infoPtr = TREEVIEW_GetInfoPtr(GetParent(hwnd));
3255     infoPtr->bIgnoreEditKillFocus = TRUE;
3256     TREEVIEW_EndEditLabelNow(infoPtr, bCancel || !infoPtr->bLabelChanged);
3257     infoPtr->bIgnoreEditKillFocus = FALSE;
3258
3259     return 0;
3260 }
3261
3262
3263 /* should handle edit control messages here */
3264
3265 static LRESULT
3266 TREEVIEW_Command(TREEVIEW_INFO *infoPtr, WPARAM wParam, LPARAM lParam)
3267 {
3268     TRACE("%x %ld\n", wParam, lParam);
3269
3270     switch (HIWORD(wParam))
3271     {
3272     case EN_UPDATE:
3273         {
3274             /* 
3275              * Adjust the edit window size 
3276              */
3277             char buffer[1024];
3278             TREEVIEW_ITEM *editItem = infoPtr->selectedItem;
3279             HDC hdc = GetDC(infoPtr->hwndEdit);
3280             SIZE sz;
3281             int len;
3282             HFONT hFont, hOldFont = 0;
3283
3284             infoPtr->bLabelChanged = TRUE;
3285
3286             len = GetWindowTextA(infoPtr->hwndEdit, buffer, sizeof(buffer));
3287
3288             /* Select font to get the right dimension of the string */
3289             hFont = SendMessageA(infoPtr->hwndEdit, WM_GETFONT, 0, 0);
3290             if (hFont != 0)
3291             {
3292                 hOldFont = SelectObject(hdc, hFont);
3293             }
3294
3295             if (GetTextExtentPoint32A(hdc, buffer, strlen(buffer), &sz))
3296             {
3297                 TEXTMETRICA textMetric;
3298
3299                 /* Add Extra spacing for the next character */
3300                 GetTextMetricsA(hdc, &textMetric);
3301                 sz.cx += (textMetric.tmMaxCharWidth * 2);
3302
3303                 sz.cx = max(sz.cx, textMetric.tmMaxCharWidth * 3);
3304                 sz.cx = min(sz.cx,
3305                             infoPtr->clientWidth - editItem->textOffset + 2);
3306
3307                 SetWindowPos(infoPtr->hwndEdit,
3308                              HWND_TOP,
3309                              0,
3310                              0,
3311                              sz.cx,
3312                              editItem->rect.bottom - editItem->rect.top + 3,
3313                              SWP_NOMOVE | SWP_DRAWFRAME);
3314             }
3315
3316             if (hFont != 0)
3317             {
3318                 SelectObject(hdc, hOldFont);
3319             }
3320
3321             ReleaseDC(infoPtr->hwnd, hdc);
3322             break;
3323         }
3324
3325     default:
3326         return SendMessageA(GetParent(infoPtr->hwnd), WM_COMMAND, wParam, lParam);
3327     }
3328
3329     return 0;
3330 }
3331
3332 static HWND
3333 TREEVIEW_EditLabelA(TREEVIEW_INFO *infoPtr, HTREEITEM hItem)
3334 {
3335     HWND hwnd = infoPtr->hwnd;
3336     HWND hwndEdit;
3337     SIZE sz;
3338     TREEVIEW_ITEM *editItem = hItem;
3339     HINSTANCE hinst = GetWindowLongA(hwnd, GWL_HINSTANCE);
3340     HDC hdc;
3341     HFONT hOldFont=0;
3342     TEXTMETRICA textMetric;
3343
3344     TRACE("%x %p\n", (unsigned)hwnd, hItem);
3345     if (!TREEVIEW_ValidItem(infoPtr, editItem))
3346         return (HWND)NULL;
3347
3348     if (infoPtr->hwndEdit)
3349         return infoPtr->hwndEdit;
3350
3351     infoPtr->bLabelChanged = FALSE;
3352
3353     /* Make sure that edit item is selected */
3354     TREEVIEW_DoSelectItem(infoPtr, TVGN_CARET, hItem, TVC_UNKNOWN);
3355     TREEVIEW_EnsureVisible(infoPtr, hItem, TRUE);
3356
3357     TREEVIEW_UpdateDispInfo(infoPtr, editItem, TVIF_TEXT);
3358
3359     hdc = GetDC(hwnd);
3360     /* Select the font to get appropriate metric dimensions */
3361     if (infoPtr->hFont != 0)
3362     {
3363         hOldFont = SelectObject(hdc, infoPtr->hFont);
3364     }
3365
3366     /* Get string length in pixels */
3367     GetTextExtentPoint32A(hdc, editItem->pszText, strlen(editItem->pszText),
3368                           &sz);
3369
3370     /* Add Extra spacing for the next character */
3371     GetTextMetricsA(hdc, &textMetric);
3372     sz.cx += (textMetric.tmMaxCharWidth * 2);
3373
3374     sz.cx = max(sz.cx, textMetric.tmMaxCharWidth * 3);
3375     sz.cx = min(sz.cx, infoPtr->clientWidth - editItem->textOffset + 2);
3376
3377     if (infoPtr->hFont != 0)
3378     {
3379         SelectObject(hdc, hOldFont);
3380     }
3381
3382     ReleaseDC(hwnd, hdc);
3383     hwndEdit = CreateWindowExA(WS_EX_LEFT,
3384                                "EDIT",
3385                                0,
3386                                WS_CHILD | WS_BORDER | ES_AUTOHSCROLL |
3387                                WS_CLIPSIBLINGS | ES_WANTRETURN |
3388                                ES_LEFT, editItem->textOffset - 2,
3389                                editItem->rect.top - 1, sz.cx + 3,
3390                                editItem->rect.bottom -
3391                                editItem->rect.top + 3, hwnd, 0, hinst, 0);
3392 /* FIXME: (HMENU)IDTVEDIT,pcs->hInstance,0); */
3393
3394     infoPtr->hwndEdit = hwndEdit;
3395
3396     /* Get a 2D border. */
3397     SetWindowLongA(hwndEdit, GWL_EXSTYLE,
3398                    GetWindowLongA(hwndEdit, GWL_EXSTYLE) & ~WS_EX_CLIENTEDGE);
3399     SetWindowLongA(hwndEdit, GWL_STYLE,
3400                    GetWindowLongA(hwndEdit, GWL_STYLE) | WS_BORDER);
3401
3402     SendMessageA(hwndEdit, WM_SETFONT, TREEVIEW_FontForItem(infoPtr, editItem),
3403                  FALSE);
3404
3405     infoPtr->wpEditOrig = (WNDPROC)SetWindowLongA(hwndEdit, GWL_WNDPROC,
3406                                                   (DWORD)
3407                                                   TREEVIEW_Edit_SubclassProc);
3408
3409     if (TREEVIEW_BeginLabelEditNotify(infoPtr, editItem))
3410     {
3411         DestroyWindow(hwndEdit);
3412         infoPtr->hwndEdit = 0;
3413         return (HWND)NULL;
3414     }
3415
3416     infoPtr->selectedItem = hItem;
3417     SetWindowTextA(hwndEdit, editItem->pszText);
3418     SetFocus(hwndEdit);
3419     SendMessageA(hwndEdit, EM_SETSEL, 0, -1);
3420     ShowWindow(hwndEdit, SW_SHOW);
3421
3422     return hwndEdit;
3423 }
3424
3425
3426 static LRESULT
3427 TREEVIEW_EndEditLabelNow(TREEVIEW_INFO *infoPtr, BOOL bCancel)
3428 {
3429     HWND hwnd = infoPtr->hwnd;
3430     TREEVIEW_ITEM *editedItem = infoPtr->selectedItem;
3431     NMTVDISPINFOA tvdi;
3432     BOOL bCommit;
3433     char tmpText[1024] = { '\0' };
3434     int iLength = 0;
3435
3436     if (!infoPtr->hwndEdit)
3437         return FALSE;
3438
3439     tvdi.hdr.hwndFrom = hwnd;
3440     tvdi.hdr.idFrom = GetWindowLongA(hwnd, GWL_ID);
3441     tvdi.hdr.code = TVN_ENDLABELEDITA;
3442     tvdi.item.mask = 0;
3443     tvdi.item.hItem = editedItem;
3444     tvdi.item.state = editedItem->state;
3445     tvdi.item.lParam = editedItem->lParam;
3446
3447     if (!bCancel)
3448     {
3449         iLength = GetWindowTextA(infoPtr->hwndEdit, tmpText, 1023);
3450
3451         if (iLength >= 1023)
3452         {
3453             ERR("Insuficient space to retrieve new item label\n");
3454         }
3455
3456         tvdi.item.pszText = tmpText;
3457         tvdi.item.cchTextMax = iLength + 1;
3458     }
3459     else
3460     {
3461         tvdi.item.pszText = NULL;
3462         tvdi.item.cchTextMax = 0;
3463     }
3464
3465     bCommit = (BOOL)SendMessageA(infoPtr->hwndNotify,
3466                                  WM_NOTIFY,
3467                                  (WPARAM)tvdi.hdr.idFrom, (LPARAM)&tvdi);
3468
3469     if (!bCancel && bCommit)    /* Apply the changes */
3470     {
3471         if (strcmp(tmpText, editedItem->pszText) != 0)
3472         {
3473             if (NULL == COMCTL32_ReAlloc(editedItem->pszText, iLength + 1))
3474             {
3475                 ERR("OutOfMemory, cannot allocate space for label\n");
3476                 DestroyWindow(infoPtr->hwndEdit);
3477                 infoPtr->hwndEdit = 0;
3478                 return FALSE;
3479             }
3480             else
3481             {
3482                 editedItem->cchTextMax = iLength + 1;
3483                 lstrcpyA(editedItem->pszText, tmpText);
3484             }
3485         }
3486     }
3487
3488     ShowWindow(infoPtr->hwndEdit, SW_HIDE);
3489     DestroyWindow(infoPtr->hwndEdit);
3490     infoPtr->hwndEdit = 0;
3491     return TRUE;
3492 }
3493
3494 static LRESULT
3495 TREEVIEW_HandleTimer(TREEVIEW_INFO *infoPtr, WPARAM wParam)
3496 {
3497     if (wParam != TV_EDIT_TIMER)
3498     {
3499         ERR("got unknown timer\n");
3500         return 1;
3501     }
3502
3503     KillTimer(infoPtr->hwnd, TV_EDIT_TIMER);
3504     infoPtr->Timer &= ~TV_EDIT_TIMER_SET;
3505
3506     TREEVIEW_EditLabelA(infoPtr, infoPtr->selectedItem);
3507
3508     return 0;
3509 }
3510
3511
3512 /* Mouse Tracking/Drag **************************************************/
3513
3514 /***************************************************************************
3515  * This is quite unusual piece of code, but that's how it's implemented in
3516  * Windows.
3517  */
3518 static LRESULT
3519 TREEVIEW_TrackMouse(TREEVIEW_INFO *infoPtr, POINT pt)
3520 {
3521     INT cxDrag = GetSystemMetrics(SM_CXDRAG);
3522     INT cyDrag = GetSystemMetrics(SM_CYDRAG);
3523     RECT r;
3524     MSG msg;
3525
3526     r.top = pt.y - cyDrag;
3527     r.left = pt.x - cxDrag;
3528     r.bottom = pt.y + cyDrag;
3529     r.right = pt.x + cxDrag;
3530
3531     SetCapture(infoPtr->hwnd);
3532
3533     while (1)
3534     {
3535         if (PeekMessageA(&msg, 0, 0, 0, PM_REMOVE | PM_NOYIELD))
3536         {
3537             if (msg.message == WM_MOUSEMOVE)
3538             {
3539                 pt.x = SLOWORD(msg.lParam);
3540                 pt.y = SHIWORD(msg.lParam);
3541                 if (PtInRect(&r, pt))
3542                     continue;
3543                 else
3544                 {
3545                     ReleaseCapture();
3546                     return 1;
3547                 }
3548             }
3549             else if (msg.message >= WM_LBUTTONDOWN &&
3550                      msg.message <= WM_RBUTTONDBLCLK)
3551             {
3552                 if (msg.message == WM_RBUTTONUP)
3553                     TREEVIEW_RButtonUp(infoPtr, &pt);
3554                 break;
3555             }
3556
3557             DispatchMessageA(&msg);
3558         }
3559
3560         if (GetCapture() != infoPtr->hwnd)
3561             return 0;
3562     }
3563
3564     ReleaseCapture();
3565     return 0;
3566 }
3567
3568
3569 static LRESULT
3570 TREEVIEW_LButtonDoubleClick(TREEVIEW_INFO *infoPtr, LPARAM lParam)
3571 {
3572     TREEVIEW_ITEM *wineItem;
3573     TVHITTESTINFO hit;
3574
3575     TRACE("\n");
3576     SetFocus(infoPtr->hwnd);
3577
3578     if (infoPtr->Timer & TV_EDIT_TIMER_SET)
3579     {
3580         /* If there is pending 'edit label' event - kill it now */
3581         KillTimer(infoPtr->hwnd, TV_EDIT_TIMER);
3582     }
3583
3584     hit.pt.x = SLOWORD(lParam);
3585     hit.pt.y = SHIWORD(lParam);
3586
3587     wineItem = (TREEVIEW_ITEM *)TREEVIEW_HitTest(infoPtr, &hit);
3588     if (!wineItem)
3589         return 0;
3590     TRACE("item %d\n", TREEVIEW_GetItemIndex(infoPtr, wineItem));
3591
3592     if (TREEVIEW_SendSimpleNotify(infoPtr, NM_DBLCLK) == FALSE)
3593     {                           /* FIXME! */
3594         switch (hit.flags)
3595         {
3596         case TVHT_ONITEMRIGHT:
3597             /* FIXME: we should not have sent NM_DBLCLK in this case. */
3598             break;
3599
3600         case TVHT_ONITEMINDENT:
3601             if (!(infoPtr->dwStyle & TVS_HASLINES))
3602             {
3603                 break;
3604             }
3605             else
3606             {
3607                 int level = hit.pt.x / infoPtr->uIndent;
3608                 if (!(infoPtr->dwStyle & TVS_LINESATROOT)) level++;
3609
3610                 while (wineItem->iLevel > level)
3611                 {
3612                     wineItem = wineItem->parent;
3613                 }
3614
3615                 /* fall through */
3616             }
3617
3618         case TVHT_ONITEMLABEL:
3619         case TVHT_ONITEMICON:
3620         case TVHT_ONITEMBUTTON:
3621             TREEVIEW_Toggle(infoPtr, wineItem, TRUE);
3622             break;
3623
3624         case TVHT_ONITEMSTATEICON:
3625            if (infoPtr->dwStyle & TVS_CHECKBOXES)
3626                TREEVIEW_ToggleItemState(infoPtr, wineItem);
3627            else
3628                TREEVIEW_Toggle(infoPtr, wineItem, TRUE);
3629            break;
3630         }
3631     }
3632     return TRUE;
3633 }
3634
3635
3636 static LRESULT
3637 TREEVIEW_LButtonDown(TREEVIEW_INFO *infoPtr, LPARAM lParam)
3638 {
3639     HWND hwnd = infoPtr->hwnd;
3640     TVHITTESTINFO ht;
3641     BOOL bTrack;
3642     HTREEITEM tempItem;
3643
3644     /* If Edit control is active - kill it and return.
3645      * The best way to do it is to set focus to itself.
3646      * Edit control subclassed procedure will automatically call
3647      * EndEditLabelNow.
3648      */
3649     if (infoPtr->hwndEdit)
3650     {
3651         SetFocus(hwnd);
3652         return 0;
3653     }
3654
3655     ht.pt.x = SLOWORD(lParam);
3656     ht.pt.y = SHIWORD(lParam);
3657
3658     TREEVIEW_HitTest(infoPtr, &ht);
3659     TRACE("item %d\n", TREEVIEW_GetItemIndex(infoPtr, ht.hItem));
3660
3661     /* update focusedItem and redraw both items */
3662     if(ht.hItem && (ht.flags & TVHT_ONITEM))
3663     {
3664         infoPtr->focusedItem = ht.hItem;
3665         InvalidateRect(hwnd, &(((HTREEITEM)(ht.hItem))->rect), TRUE);
3666
3667         if(infoPtr->selectedItem)
3668             InvalidateRect(hwnd, &(infoPtr->selectedItem->rect), TRUE);
3669     }
3670
3671     bTrack = (ht.flags & TVHT_ONITEM)
3672         && !(infoPtr->dwStyle & TVS_DISABLEDRAGDROP);
3673
3674     /* Send NM_CLICK right away */
3675     if (!bTrack)
3676         if (TREEVIEW_SendSimpleNotify(infoPtr, NM_CLICK))
3677             goto setfocus;
3678
3679     if (ht.flags & TVHT_ONITEMBUTTON)
3680     {
3681         TREEVIEW_Toggle(infoPtr, ht.hItem, TRUE);
3682         goto setfocus;
3683     }
3684     else if (bTrack)
3685     {   /* if TREEVIEW_TrackMouse == 1 dragging occured and the cursor left the dragged item's rectangle */
3686         if (TREEVIEW_TrackMouse(infoPtr, ht.pt))
3687         {
3688             TREEVIEW_SendTreeviewDnDNotify(infoPtr, TVN_BEGINDRAGA, ht.hItem,
3689                                            ht.pt);
3690             infoPtr->dropItem = ht.hItem;
3691
3692             /* clean up focusedItem as we dragged and won't select this item */
3693             if(infoPtr->focusedItem)
3694             {
3695                 /* refresh the item that was focused */
3696                 tempItem = infoPtr->focusedItem;
3697                 infoPtr->focusedItem = 0;
3698                 InvalidateRect(infoPtr->hwnd, &tempItem->rect, TRUE);
3699
3700                 /* refresh the selected item to return the filled background */
3701                 InvalidateRect(infoPtr->hwnd, &(infoPtr->selectedItem->rect), TRUE);
3702             }
3703
3704             return 0;
3705         }
3706     }
3707
3708     if (TREEVIEW_SendSimpleNotify(infoPtr, NM_CLICK))
3709         goto setfocus;
3710
3711     /* 
3712      * If the style allows editing and the node is already selected 
3713      * and the click occured on the item label...
3714      */
3715     if ((infoPtr->dwStyle & TVS_EDITLABELS) &&
3716                 (ht.flags & TVHT_ONITEMLABEL) && (infoPtr->selectedItem == ht.hItem))
3717     {
3718         if (infoPtr->Timer & TV_EDIT_TIMER_SET)
3719             KillTimer(hwnd, TV_EDIT_TIMER);
3720
3721         SetTimer(hwnd, TV_EDIT_TIMER, GetDoubleClickTime(), 0);
3722         infoPtr->Timer |= TV_EDIT_TIMER_SET;
3723     }
3724     else if (ht.flags & TVHT_ONITEM) /* select the item if the hit was inside of the icon or text */
3725     {
3726         /*
3727          * if we are TVS_SINGLEEXPAND then we want this single click to
3728          * do a bunch of things.
3729          */
3730         if((infoPtr->dwStyle & TVS_SINGLEEXPAND) &&
3731           (infoPtr->hwndEdit == 0))
3732         {
3733             TREEVIEW_ITEM *SelItem;
3734
3735             /*
3736              * Send the notification
3737              */
3738             TREEVIEW_SendTreeviewNotify(infoPtr, TVN_SINGLEEXPAND, TVIF_HANDLE | TVIF_PARAM,
3739                                 0, ht.hItem, 0);
3740
3741             /*
3742              * Close the previous selection all the way to the root
3743              * as long as the new selection is not a child
3744              */
3745             if((infoPtr->selectedItem)
3746                 && (infoPtr->selectedItem != ht.hItem))
3747             {
3748                 BOOL closeit = TRUE;
3749                 SelItem = ht.hItem;
3750
3751                 /* determine if the hitItem is a child of the currently selected item */
3752                 while(closeit && SelItem && TREEVIEW_ValidItem(infoPtr, SelItem) && (SelItem != infoPtr->root))
3753                 {
3754                     closeit = (SelItem != infoPtr->selectedItem);
3755                     SelItem = SelItem->parent;
3756                 }
3757
3758                 if(closeit)
3759                 {
3760                     if(TREEVIEW_ValidItem(infoPtr, infoPtr->selectedItem))
3761                         SelItem = infoPtr->selectedItem;
3762
3763                     while(SelItem && (SelItem != ht.hItem) && TREEVIEW_ValidItem(infoPtr, SelItem) && (SelItem != infoPtr->root))
3764                     {
3765                         TREEVIEW_Collapse(infoPtr, SelItem, FALSE, FALSE);
3766                         SelItem = SelItem->parent;
3767                     }
3768                 }
3769             }
3770
3771             /*
3772              * Expand the current item
3773              */
3774             TREEVIEW_Expand(infoPtr, ht.hItem, TVE_TOGGLE, FALSE);
3775         }
3776
3777         /* Select the current item */
3778         TREEVIEW_DoSelectItem(infoPtr, TVGN_CARET, ht.hItem, TVC_BYMOUSE);
3779     }
3780     else if (ht.flags & TVHT_ONITEMSTATEICON)
3781     {
3782         /* TVS_CHECKBOXES requires us to toggle the current state */
3783         if (infoPtr->dwStyle & TVS_CHECKBOXES)
3784             TREEVIEW_ToggleItemState(infoPtr, ht.hItem);
3785     }
3786
3787   setfocus:
3788     SetFocus(hwnd);
3789     return 0;
3790 }
3791
3792
3793 static LRESULT
3794 TREEVIEW_RButtonDown(TREEVIEW_INFO *infoPtr, LPARAM lParam)
3795 {
3796     TVHITTESTINFO ht;
3797
3798     if (infoPtr->hwndEdit)
3799     {
3800         SetFocus(infoPtr->hwnd);
3801         return 0;
3802     }
3803
3804     ht.pt.x = SLOWORD(lParam);
3805     ht.pt.y = SHIWORD(lParam);
3806
3807     TREEVIEW_HitTest(infoPtr, &ht);
3808
3809     if (TREEVIEW_TrackMouse(infoPtr, ht.pt))
3810     {
3811         if (ht.hItem)
3812         {
3813             TREEVIEW_SendTreeviewDnDNotify(infoPtr, TVN_BEGINRDRAGA, ht.hItem,
3814                                            ht.pt);
3815             infoPtr->dropItem = ht.hItem;
3816         }
3817     }
3818     else
3819     {
3820         SetFocus(infoPtr->hwnd);
3821         TREEVIEW_SendSimpleNotify(infoPtr, NM_RCLICK);
3822     }
3823
3824     return 0;
3825 }
3826
3827 static LRESULT
3828 TREEVIEW_RButtonUp(TREEVIEW_INFO *infoPtr, LPPOINT pPt)
3829 {
3830     return 0;
3831 }
3832
3833
3834 static LRESULT
3835 TREEVIEW_CreateDragImage(TREEVIEW_INFO *infoPtr, WPARAM wParam, LPARAM lParam)
3836 {
3837     TREEVIEW_ITEM *dragItem = (HTREEITEM)lParam;
3838     INT cx, cy;
3839     HDC hdc, htopdc;
3840     HWND hwtop;
3841     HBITMAP hbmp, hOldbmp;
3842     SIZE size;
3843     RECT rc;
3844     HFONT hOldFont;
3845
3846     TRACE("\n");
3847
3848     if (!(infoPtr->himlNormal))
3849         return 0;
3850
3851     if (!dragItem || !TREEVIEW_ValidItem(infoPtr, dragItem))
3852         return 0;
3853
3854     TREEVIEW_UpdateDispInfo(infoPtr, dragItem, TVIF_TEXT);
3855
3856     hwtop = GetDesktopWindow();
3857     htopdc = GetDC(hwtop);
3858     hdc = CreateCompatibleDC(htopdc);
3859
3860     hOldFont = SelectObject(hdc, infoPtr->hFont);
3861     GetTextExtentPoint32A(hdc, dragItem->pszText, lstrlenA(dragItem->pszText),
3862                           &size);
3863     TRACE("%ld %ld %s %d\n", size.cx, size.cy, dragItem->pszText,
3864           lstrlenA(dragItem->pszText));
3865     hbmp = CreateCompatibleBitmap(htopdc, size.cx, size.cy);
3866     hOldbmp = SelectObject(hdc, hbmp);
3867
3868     ImageList_GetIconSize(infoPtr->himlNormal, &cx, &cy);
3869     size.cx += cx;
3870     if (cy > size.cy)
3871         size.cy = cy;
3872
3873     infoPtr->dragList = ImageList_Create(size.cx, size.cy, ILC_COLOR, 10, 10);
3874     ImageList_Draw(infoPtr->himlNormal, dragItem->iImage, hdc, 0, 0,
3875                    ILD_NORMAL);
3876
3877 /*
3878  ImageList_GetImageInfo (infoPtr->himlNormal, dragItem->hItem, &iminfo);
3879  ImageList_AddMasked (infoPtr->dragList, iminfo.hbmImage, CLR_DEFAULT);
3880 */
3881
3882 /* draw item text */
3883
3884     SetRect(&rc, cx, 0, size.cx, size.cy);
3885     DrawTextA(hdc, dragItem->pszText, lstrlenA(dragItem->pszText), &rc,
3886               DT_LEFT);
3887     SelectObject(hdc, hOldFont);
3888     SelectObject(hdc, hOldbmp);
3889
3890     ImageList_Add(infoPtr->dragList, hbmp, 0);
3891
3892     DeleteDC(hdc);
3893     DeleteObject(hbmp);
3894     ReleaseDC(hwtop, htopdc);
3895
3896     return (LRESULT)infoPtr->dragList;
3897 }
3898
3899 /* Selection ************************************************************/
3900
3901 static LRESULT
3902 TREEVIEW_DoSelectItem(TREEVIEW_INFO *infoPtr, INT action, HTREEITEM newSelect,
3903                       INT cause)
3904 {
3905     TREEVIEW_ITEM *prevSelect;
3906     RECT rcFocused;
3907
3908     assert(newSelect == NULL || TREEVIEW_ValidItem(infoPtr, newSelect));
3909
3910     TRACE("Entering item %p (%s), flag %x, cause %x, state %d\n",
3911           newSelect, TREEVIEW_ItemName(newSelect), action, cause,
3912           newSelect ? newSelect->state : 0);
3913
3914     /* reset and redraw focusedItem if focusedItem was set so we don't */
3915     /* have to worry about the previously focused item when we set a new one */
3916     if(infoPtr->focusedItem)
3917     {
3918         rcFocused = (infoPtr->focusedItem)->rect;
3919         infoPtr->focusedItem = 0;
3920         InvalidateRect(infoPtr->hwnd, &rcFocused, TRUE);
3921     }
3922
3923     switch (action)
3924     {
3925     case TVGN_CARET:
3926         prevSelect = infoPtr->selectedItem;
3927
3928         if (prevSelect == newSelect)
3929             return FALSE;
3930
3931         if (TREEVIEW_SendTreeviewNotify(infoPtr,
3932                                         TVN_SELCHANGINGA,
3933                                         cause,
3934                                         TVIF_HANDLE | TVIF_STATE | TVIF_PARAM,
3935                                         prevSelect,
3936                                         newSelect))
3937             return FALSE;
3938
3939         if (prevSelect)
3940             prevSelect->state &= ~TVIS_SELECTED;
3941         if (newSelect)
3942             newSelect->state |= TVIS_SELECTED;
3943
3944         infoPtr->selectedItem = newSelect;
3945
3946         TREEVIEW_EnsureVisible(infoPtr, infoPtr->selectedItem, FALSE);
3947
3948         TREEVIEW_SendTreeviewNotify(infoPtr,
3949                                     TVN_SELCHANGEDA,
3950                                     cause,
3951                                     TVIF_HANDLE | TVIF_STATE | TVIF_PARAM,
3952                                     prevSelect,
3953                                     newSelect);
3954         TREEVIEW_Invalidate(infoPtr, prevSelect);
3955         TREEVIEW_Invalidate(infoPtr, newSelect);
3956         break;
3957
3958     case TVGN_DROPHILITE:
3959         prevSelect = infoPtr->dropItem;
3960
3961         if (prevSelect)
3962             prevSelect->state &= ~TVIS_DROPHILITED;
3963
3964         infoPtr->dropItem = newSelect;
3965
3966         if (newSelect)
3967             newSelect->state |= TVIS_DROPHILITED;
3968
3969         TREEVIEW_Invalidate(infoPtr, prevSelect);
3970         TREEVIEW_Invalidate(infoPtr, newSelect);
3971         break;
3972
3973     case TVGN_FIRSTVISIBLE:
3974         TREEVIEW_EnsureVisible(infoPtr, newSelect, FALSE);
3975         TREEVIEW_SetFirstVisible(infoPtr, newSelect, TRUE);
3976         TREEVIEW_Invalidate(infoPtr, NULL);
3977         break;
3978     }
3979
3980     TRACE("Leaving state %d\n", newSelect ? newSelect->state : 0);
3981     return TRUE;
3982 }
3983
3984 /* FIXME: handle NM_KILLFOCUS etc */
3985 static LRESULT
3986 TREEVIEW_SelectItem(TREEVIEW_INFO *infoPtr, INT wParam, HTREEITEM item)
3987 {
3988     if (item != NULL && !TREEVIEW_ValidItem(infoPtr, item))
3989         return FALSE;
3990
3991     TRACE("%p (%s) %d\n", item, TREEVIEW_ItemName(item), wParam);
3992
3993     if (!TREEVIEW_DoSelectItem(infoPtr, wParam, item, TVC_UNKNOWN))
3994         return FALSE;
3995
3996     return TRUE;
3997 }
3998
3999 /*************************************************************************
4000  *              TREEVIEW_ProcessLetterKeys
4001  *
4002  *  Processes keyboard messages generated by pressing the letter keys 
4003  *  on the keyboard.
4004  *  What this does is perform a case insensitive search from the 
4005  *  current position with the following quirks:
4006  *  - If two chars or more are pressed in quick succession we search 
4007  *    for the corresponding string (e.g. 'abc').
4008  *  - If there is a delay we wipe away the current search string and 
4009  *    restart with just that char.
4010  *  - If the user keeps pressing the same character, whether slowly or 
4011  *    fast, so that the search string is entirely composed of this 
4012  *    character ('aaaaa' for instance), then we search for first item 
4013  *    that starting with that character.
4014  *  - If the user types the above character in quick succession, then 
4015  *    we must also search for the corresponding string ('aaaaa'), and 
4016  *    go to that string if there is a match.
4017  *
4018  * RETURNS
4019  *
4020  *  Zero.
4021  *
4022  * BUGS
4023  *
4024  *  - The current implementation has a list of characters it will 
4025  *    accept and it ignores averything else. In particular it will 
4026  *    ignore accentuated characters which seems to match what 
4027  *    Windows does. But I'm not sure it makes sense to follow 
4028  *    Windows there.
4029  *  - We don't sound a beep when the search fails.
4030  *  - The search should start from the focused item, not from the selected 
4031  *    item. One reason for this is to allow for multiple selections in trees.
4032  *    But currently infoPtr->focusedItem does not seem very usable.
4033  *
4034  * SEE ALSO
4035  *
4036  *  TREEVIEW_ProcessLetterKeys
4037  */
4038 static INT TREEVIEW_ProcessLetterKeys(
4039     HWND hwnd, /* handle to the window */
4040     WPARAM charCode, /* the character code, the actual character */
4041     LPARAM keyData /* key data */
4042     )
4043 {
4044     TREEVIEW_INFO *infoPtr;
4045     HTREEITEM nItem;
4046     HTREEITEM endidx,idx;
4047     TVITEMEXA item;
4048     CHAR buffer[MAX_PATH];
4049     DWORD timestamp,elapsed;
4050
4051     /* simple parameter checking */
4052     if (!hwnd || !charCode || !keyData)
4053         return 0;
4054
4055     infoPtr=(TREEVIEW_INFO*)GetWindowLongA(hwnd, 0);
4056     if (!infoPtr)
4057         return 0;
4058
4059     /* only allow the valid WM_CHARs through */
4060     if (!isalnum(charCode) &&
4061         charCode != '.' && charCode != '`' && charCode != '!' &&
4062         charCode != '@' && charCode != '#' && charCode != '$' &&
4063         charCode != '%' && charCode != '^' && charCode != '&' &&
4064         charCode != '*' && charCode != '(' && charCode != ')' &&
4065         charCode != '-' && charCode != '_' && charCode != '+' &&
4066         charCode != '=' && charCode != '\\'&& charCode != ']' &&
4067         charCode != '}' && charCode != '[' && charCode != '{' &&
4068         charCode != '/' && charCode != '?' && charCode != '>' &&
4069         charCode != '<' && charCode != ',' && charCode != '~')
4070         return 0;
4071
4072     /* compute how much time elapsed since last keypress */
4073     timestamp = GetTickCount();
4074     if (timestamp > infoPtr->lastKeyPressTimestamp) {
4075         elapsed=timestamp-infoPtr->lastKeyPressTimestamp;
4076     } else {
4077         elapsed=infoPtr->lastKeyPressTimestamp-timestamp;
4078     }
4079
4080     /* update the search parameters */
4081     infoPtr->lastKeyPressTimestamp=timestamp;
4082     if (elapsed < KEY_DELAY) {
4083         if (infoPtr->nSearchParamLength < sizeof(infoPtr->szSearchParam)) {
4084             infoPtr->szSearchParam[infoPtr->nSearchParamLength++]=charCode;
4085         }
4086         if (infoPtr->charCode != charCode) {
4087             infoPtr->charCode=charCode=0;
4088         }
4089     } else {
4090         infoPtr->charCode=charCode;
4091         infoPtr->szSearchParam[0]=charCode;
4092         infoPtr->nSearchParamLength=1;
4093         /* Redundant with the 1 char string */
4094         charCode=0;
4095     }
4096
4097     /* and search from the current position */
4098     nItem=NULL;
4099     if (infoPtr->selectedItem != NULL) {
4100         endidx=infoPtr->selectedItem;
4101         /* if looking for single character match,
4102          * then we must always move forward
4103          */
4104         if (infoPtr->nSearchParamLength == 1)
4105             idx=TREEVIEW_GetNextListItem(infoPtr,endidx);
4106         else
4107             idx=endidx;
4108     } else {
4109         endidx=NULL;
4110         idx=infoPtr->root->firstChild;
4111     }
4112     do {
4113         if (idx == NULL) {
4114             if (endidx == NULL)
4115                 break;
4116             idx=infoPtr->root->firstChild;
4117         }
4118
4119         /* get item */
4120         ZeroMemory(&item, sizeof(item));
4121         item.mask = TVIF_TEXT;
4122         item.hItem = idx;
4123         item.pszText = buffer;
4124         item.cchTextMax = sizeof(buffer);
4125         TREEVIEW_GetItemA( infoPtr, &item );
4126
4127         /* check for a match */
4128         if (strncasecmp(item.pszText,infoPtr->szSearchParam,infoPtr->nSearchParamLength) == 0) {
4129             nItem=idx;
4130             break;
4131         } else if ( (charCode != 0) && (nItem == NULL) &&
4132                     (nItem != infoPtr->selectedItem) &&
4133                     (strncasecmp(item.pszText,infoPtr->szSearchParam,1) == 0) ) {
4134             /* This would work but we must keep looking for a longer match */
4135             nItem=idx;
4136         }
4137         idx=TREEVIEW_GetNextListItem(infoPtr,idx);
4138     } while (idx != endidx);
4139
4140     if (nItem != NULL) {
4141         if (TREEVIEW_DoSelectItem(infoPtr, TVGN_CARET, nItem, TVC_BYKEYBOARD)) {
4142             TREEVIEW_EnsureVisible(infoPtr, nItem, FALSE);
4143         }
4144     }
4145
4146     return 0;
4147 }
4148
4149 /* Scrolling ************************************************************/
4150
4151 static LRESULT
4152 TREEVIEW_EnsureVisible(TREEVIEW_INFO *infoPtr, HTREEITEM item, BOOL bHScroll)
4153 {
4154     HTREEITEM newFirstVisible = NULL;
4155     int visible_pos;
4156
4157     if (!TREEVIEW_ValidItem(infoPtr, item))
4158         return FALSE;
4159
4160     if (!ISVISIBLE(item))
4161     {
4162         /* Expand parents as necessary. */
4163         HTREEITEM parent;
4164
4165         /* see if we are trying to ensure that root is vislble */
4166         if((item != infoPtr->root) && TREEVIEW_ValidItem(infoPtr, item))
4167           parent = item->parent;
4168         else
4169           parent = item; /* this item is the topmost item */
4170
4171         while (parent != infoPtr->root)
4172         {
4173             if (!(parent->state & TVIS_EXPANDED))
4174                 TREEVIEW_Expand(infoPtr, parent, FALSE, FALSE);
4175
4176             parent = parent->parent;
4177         }
4178     }
4179
4180     TRACE("%p (%s) %ld - %ld\n", item, TREEVIEW_ItemName(item), item->visibleOrder,
4181           infoPtr->firstVisible->visibleOrder);
4182
4183     visible_pos = item->visibleOrder - infoPtr->firstVisible->visibleOrder;
4184
4185     if (visible_pos < 0)
4186     {
4187         /* item is before the start of the list: put it at the top. */
4188         newFirstVisible = item;
4189     }
4190     else if (visible_pos >= TREEVIEW_GetVisibleCount(infoPtr)
4191              /* Sometimes, before we are displayed, GVC is 0, causing us to
4192               * spuriously scroll up. */
4193              && visible_pos > 0)
4194     {
4195         /* item is past the end of the list. */
4196         int scroll = visible_pos - TREEVIEW_GetVisibleCount(infoPtr);
4197
4198         newFirstVisible = TREEVIEW_GetListItem(infoPtr, infoPtr->firstVisible,
4199                                                scroll + 1);
4200     }
4201
4202     if (bHScroll)
4203     {
4204         /* Scroll window so item's text is visible as much as possible */
4205         /* Calculation of amount of extra space is taken from EditLabel code */
4206         INT pos, x;
4207         TEXTMETRICA textMetric;
4208         HDC hdc = GetWindowDC(infoPtr->hwnd);
4209
4210         x = item->textWidth;
4211
4212         GetTextMetricsA(hdc, &textMetric);
4213         ReleaseDC(infoPtr->hwnd, hdc);
4214
4215         x += (textMetric.tmMaxCharWidth * 2);
4216         x = max(x, textMetric.tmMaxCharWidth * 3);
4217
4218         if (item->textOffset < 0)
4219            pos = item->textOffset;
4220         else if (item->textOffset + x > infoPtr->clientWidth)
4221         {
4222            if (x > infoPtr->clientWidth)
4223               pos = item->textOffset;
4224            else
4225               pos = item->textOffset + x - infoPtr->clientWidth;
4226         }
4227         else
4228            pos = 0;
4229
4230         TREEVIEW_HScroll(infoPtr, MAKEWPARAM(SB_THUMBPOSITION, infoPtr->scrollX + pos));
4231     }
4232
4233     if (newFirstVisible != NULL && newFirstVisible != infoPtr->firstVisible)
4234     {
4235         TREEVIEW_SetFirstVisible(infoPtr, newFirstVisible, TRUE);
4236
4237         return TRUE;
4238     }
4239
4240     return FALSE;
4241 }
4242
4243 static VOID
4244 TREEVIEW_SetFirstVisible(TREEVIEW_INFO *infoPtr,
4245                          TREEVIEW_ITEM *newFirstVisible,
4246                          BOOL bUpdateScrollPos)
4247 {
4248     int gap_size;
4249
4250     TRACE("%p: %s\n", newFirstVisible, TREEVIEW_ItemName(newFirstVisible));
4251
4252     if (newFirstVisible != NULL)
4253     {
4254         /* Prevent an empty gap from appearing at the bottom... */
4255         gap_size = TREEVIEW_GetVisibleCount(infoPtr)
4256             - infoPtr->maxVisibleOrder + newFirstVisible->visibleOrder;
4257
4258         if (gap_size > 0)
4259         {
4260             newFirstVisible = TREEVIEW_GetListItem(infoPtr, newFirstVisible,
4261                                                    -gap_size);
4262
4263             /* ... unless we just don't have enough items. */
4264             if (newFirstVisible == NULL)
4265                 newFirstVisible = infoPtr->root->firstChild;
4266         }
4267     }
4268
4269     if (infoPtr->firstVisible != newFirstVisible)
4270     {
4271         if (infoPtr->firstVisible == NULL || newFirstVisible == NULL)
4272         {
4273             infoPtr->firstVisible = newFirstVisible;
4274             TREEVIEW_Invalidate(infoPtr, NULL);
4275         }
4276         else
4277         {
4278             TREEVIEW_ITEM *item;
4279             int scroll = infoPtr->uItemHeight *
4280                          (infoPtr->firstVisible->visibleOrder
4281                           - newFirstVisible->visibleOrder);
4282
4283             infoPtr->firstVisible = newFirstVisible;
4284
4285             for (item = infoPtr->root->firstChild; item != NULL;
4286                  item = TREEVIEW_GetNextListItem(infoPtr, item))
4287             {
4288                item->rect.top += scroll;
4289                item->rect.bottom += scroll;
4290             }
4291
4292             if (bUpdateScrollPos)
4293                 SetScrollPos(infoPtr->hwnd, SB_VERT,
4294                               newFirstVisible->visibleOrder, TRUE);
4295
4296             ScrollWindow(infoPtr->hwnd, 0, scroll, NULL, NULL);
4297             UpdateWindow(infoPtr->hwnd);
4298         }
4299     }
4300 }
4301
4302 /************************************************************************
4303  * VScroll is always in units of visible items. i.e. we always have a
4304  * visible item aligned to the top of the control. (Unless we have no
4305  * items at all.)
4306  */
4307 static LRESULT
4308 TREEVIEW_VScroll(TREEVIEW_INFO *infoPtr, WPARAM wParam)
4309 {
4310     TREEVIEW_ITEM *oldFirstVisible = infoPtr->firstVisible;
4311     TREEVIEW_ITEM *newFirstVisible = NULL;
4312
4313     int nScrollCode = LOWORD(wParam);
4314
4315     TRACE("wp %x\n", wParam);
4316
4317     if (!(infoPtr->uInternalStatus & TV_VSCROLL))
4318         return 0;
4319
4320     if (infoPtr->hwndEdit)
4321         SetFocus(infoPtr->hwnd);
4322
4323     if (!oldFirstVisible)
4324     {
4325         assert(infoPtr->root->firstChild == NULL);
4326         return 0;
4327     }
4328
4329     switch (nScrollCode)
4330     {
4331     case SB_TOP:
4332         newFirstVisible = infoPtr->root->firstChild;
4333         break;
4334
4335     case SB_BOTTOM:
4336         newFirstVisible = TREEVIEW_GetLastListItem(infoPtr, infoPtr->root);
4337         break;
4338
4339     case SB_LINEUP:
4340         newFirstVisible = TREEVIEW_GetPrevListItem(infoPtr, oldFirstVisible);
4341         break;
4342
4343     case SB_LINEDOWN:
4344         newFirstVisible = TREEVIEW_GetNextListItem(infoPtr, oldFirstVisible);
4345         break;
4346
4347     case SB_PAGEUP:
4348         newFirstVisible = TREEVIEW_GetListItem(infoPtr, oldFirstVisible,
4349                                                -max(1, TREEVIEW_GetVisibleCount(infoPtr)));
4350         break;
4351
4352     case SB_PAGEDOWN:
4353         newFirstVisible = TREEVIEW_GetListItem(infoPtr, oldFirstVisible,
4354                                                max(1, TREEVIEW_GetVisibleCount(infoPtr)));
4355         break;
4356
4357     case SB_THUMBTRACK:
4358     case SB_THUMBPOSITION:
4359         newFirstVisible = TREEVIEW_GetListItem(infoPtr,
4360                                                infoPtr->root->firstChild,
4361                                                (LONG)(SHORT)HIWORD(wParam));
4362         break;
4363
4364     case SB_ENDSCROLL:
4365         return 0;
4366     }
4367
4368     if (newFirstVisible != NULL)
4369     {
4370         if (newFirstVisible != oldFirstVisible)
4371             TREEVIEW_SetFirstVisible(infoPtr, newFirstVisible,
4372                                   nScrollCode != SB_THUMBTRACK);
4373         else if (nScrollCode == SB_THUMBPOSITION)
4374             SetScrollPos(infoPtr->hwnd, SB_VERT,
4375                          newFirstVisible->visibleOrder, TRUE);
4376     }
4377
4378     return 0;
4379 }
4380
4381 static LRESULT
4382 TREEVIEW_HScroll(TREEVIEW_INFO *infoPtr, WPARAM wParam)
4383 {
4384     int maxWidth;
4385     int scrollX = infoPtr->scrollX;
4386     int nScrollCode = LOWORD(wParam);
4387
4388     TRACE("wp %x\n", wParam);
4389
4390     if (!(infoPtr->uInternalStatus & TV_HSCROLL))
4391         return FALSE;
4392
4393     if (infoPtr->hwndEdit)
4394         SetFocus(infoPtr->hwnd);
4395
4396     maxWidth = infoPtr->treeWidth - infoPtr->clientWidth;
4397     /* shall never occur */
4398     if (maxWidth <= 0)
4399     {
4400        scrollX = 0;
4401        goto scroll;
4402     }
4403
4404     switch (nScrollCode)
4405     {
4406     case SB_LINELEFT:
4407         scrollX -= infoPtr->uItemHeight;
4408         break;
4409     case SB_LINERIGHT:
4410         scrollX += infoPtr->uItemHeight;
4411         break;
4412     case SB_PAGELEFT:
4413         scrollX -= infoPtr->clientWidth;
4414         break;
4415     case SB_PAGERIGHT:
4416         scrollX += infoPtr->clientWidth;
4417         break;
4418
4419     case SB_THUMBTRACK:
4420     case SB_THUMBPOSITION:
4421         scrollX = (int)(SHORT)HIWORD(wParam);
4422         break;
4423
4424     case SB_ENDSCROLL:
4425        return 0;
4426     }
4427
4428     if (scrollX > maxWidth)
4429         scrollX = maxWidth;
4430     else if (scrollX < 0)
4431         scrollX = 0;
4432
4433 scroll:
4434     if (scrollX != infoPtr->scrollX)
4435     {
4436         TREEVIEW_ITEM *item;
4437         LONG scroll_pixels = infoPtr->scrollX - scrollX;
4438         
4439         for (item = infoPtr->root->firstChild; item != NULL;
4440              item = TREEVIEW_GetNextListItem(infoPtr, item))
4441         {
4442            item->linesOffset += scroll_pixels;
4443            item->stateOffset += scroll_pixels;
4444            item->imageOffset += scroll_pixels;
4445            item->textOffset  += scroll_pixels;
4446         }
4447
4448         ScrollWindow(infoPtr->hwnd, scroll_pixels, 0, NULL, NULL);
4449         infoPtr->scrollX = scrollX;
4450         UpdateWindow(infoPtr->hwnd);
4451     }
4452
4453     if (nScrollCode != SB_THUMBTRACK)
4454        SetScrollPos(infoPtr->hwnd, SB_HORZ, scrollX, TRUE);
4455
4456     return 0;
4457 }
4458
4459 static LRESULT
4460 TREEVIEW_MouseWheel(TREEVIEW_INFO *infoPtr, WPARAM wParam)
4461 {
4462     short gcWheelDelta;
4463     UINT pulScrollLines = 3;
4464
4465     if (infoPtr->firstVisible == NULL)
4466         return TRUE;
4467
4468     SystemParametersInfoW(SPI_GETWHEELSCROLLLINES, 0, &pulScrollLines, 0);
4469
4470     gcWheelDelta = -(short)HIWORD(wParam);
4471     pulScrollLines *= (gcWheelDelta / WHEEL_DELTA);
4472
4473     if (abs(gcWheelDelta) >= WHEEL_DELTA && pulScrollLines)
4474     {
4475         int newDy = infoPtr->firstVisible->visibleOrder + pulScrollLines;
4476         int maxDy = infoPtr->maxVisibleOrder;
4477
4478         if (newDy > maxDy)
4479             newDy = maxDy;
4480
4481         if (newDy < 0)
4482             newDy = 0;
4483
4484         TREEVIEW_VScroll(infoPtr, MAKEWPARAM(SB_THUMBPOSITION, newDy));
4485     }
4486     return TRUE;
4487 }
4488
4489 /* Create/Destroy *******************************************************/
4490
4491 static LRESULT
4492 TREEVIEW_Create(HWND hwnd)
4493
4494     RECT rcClient;
4495     TREEVIEW_INFO *infoPtr;
4496
4497     TRACE("wnd %x, style %lx\n", hwnd, GetWindowLongA(hwnd, GWL_STYLE));
4498
4499     infoPtr = (TREEVIEW_INFO *)COMCTL32_Alloc(sizeof(TREEVIEW_INFO));
4500  
4501     if (infoPtr == NULL)
4502     {
4503         ERR("could not allocate info memory!\n");
4504         return 0;
4505     }
4506
4507     SetWindowLongA(hwnd, 0, (DWORD)infoPtr);
4508
4509     infoPtr->hwnd = hwnd;
4510     infoPtr->dwStyle = GetWindowLongA(hwnd, GWL_STYLE);
4511     infoPtr->uInternalStatus = 0;
4512     infoPtr->Timer = 0;
4513     infoPtr->uNumItems = 0;
4514     infoPtr->cdmode = 0;
4515     infoPtr->uScrollTime = 300; /* milliseconds */
4516     infoPtr->bRedraw = TRUE;
4517
4518     GetClientRect(hwnd, &rcClient);
4519
4520     /* No scroll bars yet. */
4521     infoPtr->clientWidth = rcClient.right;
4522     infoPtr->clientHeight = rcClient.bottom;
4523
4524     infoPtr->treeWidth = 0;
4525     infoPtr->treeHeight = 0;
4526
4527     infoPtr->uIndent = 19;
4528     infoPtr->selectedItem = 0;
4529     infoPtr->focusedItem = 0;
4530     /* hotItem? */
4531     infoPtr->firstVisible = 0;
4532     infoPtr->maxVisibleOrder = 0;
4533     infoPtr->dropItem = 0;
4534     infoPtr->insertMarkItem = 0;
4535     infoPtr->insertBeforeorAfter = 0;
4536     /* dragList */
4537
4538     infoPtr->scrollX = 0;
4539
4540     infoPtr->clrBk = GetSysColor(COLOR_WINDOW);
4541     infoPtr->clrText = -1;      /* use system color */
4542     infoPtr->clrLine = RGB(128, 128, 128);
4543     infoPtr->clrInsertMark = GetSysColor(COLOR_BTNTEXT);
4544
4545     /* hwndToolTip */
4546
4547     infoPtr->hwndEdit = 0;
4548     infoPtr->wpEditOrig = NULL;
4549     infoPtr->bIgnoreEditKillFocus = FALSE;
4550     infoPtr->bLabelChanged = FALSE;
4551
4552     infoPtr->himlNormal = NULL;
4553     infoPtr->himlState = NULL;
4554     infoPtr->normalImageWidth = 0;
4555     infoPtr->normalImageHeight = 0;
4556     infoPtr->stateImageWidth = 0;
4557     infoPtr->stateImageHeight = 0;
4558
4559     infoPtr->items = DPA_Create(16);
4560
4561     infoPtr->hFont = GetStockObject(DEFAULT_GUI_FONT);
4562     infoPtr->hBoldFont = TREEVIEW_CreateBoldFont(infoPtr->hFont);
4563
4564     infoPtr->uItemHeight = TREEVIEW_NaturalHeight(infoPtr);
4565
4566     infoPtr->root = TREEVIEW_AllocateItem(infoPtr);
4567     infoPtr->root->state = TVIS_EXPANDED;
4568     infoPtr->root->iLevel = -1;
4569     infoPtr->root->visibleOrder = -1;
4570
4571     infoPtr->hwndNotify = GetParent(hwnd);
4572 #if 0
4573     infoPtr->bTransparent = ( GetWindowLongA( hwnd, GWL_STYLE) & TBSTYLE_FLAT);
4574 #endif
4575
4576     infoPtr->hwndToolTip = 0;
4577     if (!(infoPtr->dwStyle & TVS_NOTOOLTIPS))
4578         infoPtr->hwndToolTip = COMCTL32_CreateToolTip(hwnd);
4579
4580     if (infoPtr->dwStyle & TVS_CHECKBOXES)
4581     {
4582         RECT rc;
4583         HBITMAP hbm, hbmOld;
4584         HDC hdc;
4585         int nIndex;
4586
4587         infoPtr->himlState =
4588             ImageList_Create(16, 16, ILC_COLOR | ILC_MASK, 3, 0);
4589
4590         hdc = CreateCompatibleDC(0);
4591         hbm = CreateCompatibleBitmap(hdc, 48, 16);
4592         hbmOld = SelectObject(hdc, hbm);
4593
4594         rc.left  = 0;   rc.top    = 0;
4595         rc.right = 48;  rc.bottom = 16;
4596         FillRect(hdc, &rc, (HBRUSH)(COLOR_WINDOW+1));
4597
4598         rc.left  = 18;   rc.top    = 2;
4599         rc.right = 30;   rc.bottom = 14;
4600         DrawFrameControl(hdc, &rc, DFC_BUTTON,
4601                           DFCS_BUTTONCHECK|DFCS_FLAT);
4602
4603         rc.left  = 34;   rc.right  = 46;
4604         DrawFrameControl(hdc, &rc, DFC_BUTTON,
4605                           DFCS_BUTTONCHECK|DFCS_FLAT|DFCS_CHECKED);
4606
4607         nIndex = ImageList_AddMasked(infoPtr->himlState, hbm,
4608                                       GetSysColor(COLOR_WINDOW));
4609         TRACE("chckbox index %d\n", nIndex);
4610         SelectObject(hdc, hbmOld);
4611         DeleteObject(hbm);
4612         DeleteDC(hdc);
4613
4614         infoPtr->stateImageWidth = 16;
4615         infoPtr->stateImageHeight = 16;
4616     }
4617     return 0;
4618 }
4619
4620
4621 static LRESULT
4622 TREEVIEW_Destroy(TREEVIEW_INFO *infoPtr)
4623 {
4624     TRACE("\n");
4625
4626     TREEVIEW_RemoveTree(infoPtr);
4627
4628     /* tool tip is automatically destroyed: we are its owner */
4629
4630     /* Restore original windproc. */
4631     if (infoPtr->hwndEdit)
4632         SetWindowLongA(infoPtr->hwndEdit, GWL_WNDPROC,
4633                        (LONG)infoPtr->wpEditOrig);
4634
4635     /* Deassociate treeview from the window before doing anything drastic. */
4636     SetWindowLongA(infoPtr->hwnd, 0, (LONG)NULL);
4637
4638     DeleteObject(infoPtr->hBoldFont);
4639     COMCTL32_Free(infoPtr);
4640
4641     return 0;
4642 }
4643
4644 /* Miscellaneous Messages ***********************************************/
4645
4646 static LRESULT
4647 TREEVIEW_ScrollKeyDown(TREEVIEW_INFO *infoPtr, WPARAM key)
4648 {
4649     static const struct
4650     {
4651         unsigned char code;
4652     }
4653     scroll[] =
4654     {
4655 #define SCROLL_ENTRY(dir, code) { ((dir) << 7) | (code) }
4656         SCROLL_ENTRY(SB_VERT, SB_PAGEUP),       /* VK_PRIOR */
4657         SCROLL_ENTRY(SB_VERT, SB_PAGEDOWN),     /* VK_NEXT */
4658         SCROLL_ENTRY(SB_VERT, SB_BOTTOM),       /* VK_END */
4659         SCROLL_ENTRY(SB_VERT, SB_TOP),          /* VK_HOME */
4660         SCROLL_ENTRY(SB_HORZ, SB_LINEUP),       /* VK_LEFT */
4661         SCROLL_ENTRY(SB_VERT, SB_LINEUP),       /* VK_UP */
4662         SCROLL_ENTRY(SB_HORZ, SB_LINEDOWN),     /* VK_RIGHT */
4663         SCROLL_ENTRY(SB_VERT, SB_LINEDOWN)      /* VK_DOWN */
4664 #undef SCROLL_ENTRY
4665     };
4666
4667     if (key >= VK_PRIOR && key <= VK_DOWN)
4668     {
4669         unsigned char code = scroll[key - VK_PRIOR].code;
4670
4671         (((code & (1 << 7)) == (SB_HORZ << 7))
4672          ? TREEVIEW_HScroll
4673          : TREEVIEW_VScroll)(infoPtr, code & 0x7F);
4674     }
4675
4676     return 0;
4677 }
4678
4679 /************************************************************************
4680  *        TREEVIEW_KeyDown
4681  *
4682  * VK_UP       Move selection to the previous non-hidden item.
4683  * VK_DOWN     Move selection to the next non-hidden item.
4684  * VK_HOME     Move selection to the first item.
4685  * VK_END      Move selection to the last item.
4686  * VK_LEFT     If expanded then collapse, otherwise move to parent.
4687  * VK_RIGHT    If collapsed then expand, otherwise move to first child.
4688  * VK_ADD      Expand.
4689  * VK_SUBTRACT Collapse.
4690  * VK_MULTIPLY Expand all.
4691  * VK_PRIOR    Move up GetVisibleCount items.
4692  * VK_NEXT     Move down GetVisibleCount items.
4693  * VK_BACK     Move to parent.
4694  * CTRL-Left,Right,Up,Down,PgUp,PgDown,Home,End: Scroll without changing selection
4695  */
4696 static LRESULT
4697 TREEVIEW_KeyDown(TREEVIEW_INFO *infoPtr, WPARAM wParam)
4698 {
4699     /* If it is non-NULL and different, it will be selected and visible. */
4700     TREEVIEW_ITEM *newSelection = NULL;
4701
4702     TREEVIEW_ITEM *prevItem = infoPtr->selectedItem;
4703
4704     TRACE("%x\n", wParam);
4705
4706     if (prevItem == NULL)
4707         return FALSE;
4708
4709     if (GetAsyncKeyState(VK_CONTROL) & 0x8000)
4710         return TREEVIEW_ScrollKeyDown(infoPtr, wParam);
4711
4712     switch (wParam)
4713     {
4714     case VK_UP:
4715         newSelection = TREEVIEW_GetPrevListItem(infoPtr, prevItem);
4716         if (!newSelection)
4717             newSelection = infoPtr->root->firstChild;
4718         break;
4719
4720     case VK_DOWN:
4721         newSelection = TREEVIEW_GetNextListItem(infoPtr, prevItem);
4722         break;
4723
4724     case VK_HOME:
4725         newSelection = infoPtr->root->firstChild;
4726         break;
4727
4728     case VK_END:
4729         newSelection = TREEVIEW_GetLastListItem(infoPtr, infoPtr->root);
4730         break;
4731
4732     case VK_LEFT:
4733         if (prevItem->state & TVIS_EXPANDED)
4734         {
4735             TREEVIEW_Collapse(infoPtr, prevItem, FALSE, TRUE);
4736         }
4737         else if (prevItem->parent != infoPtr->root)
4738         {
4739             newSelection = prevItem->parent;
4740         }
4741         break;
4742
4743     case VK_RIGHT:
4744         if (TREEVIEW_HasChildren(infoPtr, prevItem))
4745         {
4746             if (!(prevItem->state & TVIS_EXPANDED))
4747                 TREEVIEW_Expand(infoPtr, prevItem, FALSE, TRUE);
4748             else
4749             {
4750                 newSelection = prevItem->firstChild;
4751             }
4752         }
4753
4754         break;
4755
4756     case VK_MULTIPLY:
4757         TREEVIEW_ExpandAll(infoPtr, prevItem);
4758         break;
4759
4760     case VK_ADD:
4761         if (!(prevItem->state & TVIS_EXPANDED))
4762             TREEVIEW_Expand(infoPtr, prevItem, FALSE, TRUE);
4763         break;
4764
4765     case VK_SUBTRACT:
4766         if (prevItem->state & TVIS_EXPANDED)
4767             TREEVIEW_Collapse(infoPtr, prevItem, FALSE, TRUE);
4768         break;
4769
4770     case VK_PRIOR:
4771         newSelection
4772             = TREEVIEW_GetListItem(infoPtr, prevItem,
4773                                    -TREEVIEW_GetVisibleCount(infoPtr));
4774         break;
4775
4776     case VK_NEXT:
4777         newSelection
4778             = TREEVIEW_GetListItem(infoPtr, prevItem,
4779                                    TREEVIEW_GetVisibleCount(infoPtr));
4780         break;
4781
4782     case VK_BACK:
4783         newSelection = prevItem->parent;
4784         if (newSelection == infoPtr->root)
4785             newSelection = NULL;
4786         break;
4787
4788     case VK_SPACE:
4789         if (infoPtr->dwStyle & TVS_CHECKBOXES)
4790             TREEVIEW_ToggleItemState(infoPtr, prevItem);
4791         break;
4792     }
4793
4794     if (newSelection && newSelection != prevItem)
4795     {
4796         if (TREEVIEW_DoSelectItem(infoPtr, TVGN_CARET, newSelection,
4797                                   TVC_BYKEYBOARD))
4798         {
4799             TREEVIEW_EnsureVisible(infoPtr, newSelection, FALSE);
4800         }
4801     }
4802
4803     return FALSE;
4804 }
4805
4806 static LRESULT
4807 TREEVIEW_Size(TREEVIEW_INFO *infoPtr, WPARAM wParam, LPARAM lParam)
4808 {
4809     if (wParam == SIZE_RESTORED)
4810     {
4811         infoPtr->clientWidth  = SLOWORD(lParam);
4812         infoPtr->clientHeight = SHIWORD(lParam);
4813
4814         TREEVIEW_RecalculateVisibleOrder(infoPtr, NULL);
4815         TREEVIEW_SetFirstVisible(infoPtr, infoPtr->firstVisible, TRUE);
4816         TREEVIEW_UpdateScrollBars(infoPtr);
4817     }
4818     else
4819     {
4820         FIXME("WM_SIZE flag %x %lx not handled\n", wParam, lParam);
4821     }
4822
4823     TREEVIEW_Invalidate(infoPtr, NULL);
4824     return 0;
4825 }
4826
4827 static LRESULT
4828 TREEVIEW_StyleChanged(TREEVIEW_INFO *infoPtr, WPARAM wParam, LPARAM lParam)
4829 {
4830     TRACE("(%x %lx)\n", wParam, lParam);
4831
4832     if (wParam == GWL_STYLE)
4833     {
4834        DWORD dwNewStyle = ((LPSTYLESTRUCT)lParam)->styleNew;
4835
4836        /* we have to take special care about tooltips */
4837        if ((infoPtr->dwStyle ^ dwNewStyle) & TVS_NOTOOLTIPS)
4838        {
4839           if (infoPtr->dwStyle & TVS_NOTOOLTIPS)
4840           {
4841               infoPtr->hwndToolTip = COMCTL32_CreateToolTip(infoPtr->hwnd);
4842               TRACE("\n");
4843           }
4844           else
4845           {
4846              DestroyWindow(infoPtr->hwndToolTip);
4847              infoPtr->hwndToolTip = 0;
4848           }
4849        }
4850
4851        infoPtr->dwStyle = dwNewStyle;
4852     }
4853
4854     TREEVIEW_UpdateSubTree(infoPtr, infoPtr->root);
4855     TREEVIEW_UpdateScrollBars(infoPtr);
4856     TREEVIEW_Invalidate(infoPtr, NULL);
4857
4858     return 0;
4859 }
4860
4861 static LRESULT
4862 TREEVIEW_SetFocus(TREEVIEW_INFO *infoPtr)
4863 {
4864     TRACE("\n");
4865
4866     if (!infoPtr->selectedItem)
4867     {
4868         TREEVIEW_DoSelectItem(infoPtr, TVGN_CARET, infoPtr->firstVisible,
4869                               TVC_UNKNOWN);
4870     }
4871
4872     TREEVIEW_SendSimpleNotify(infoPtr, NM_SETFOCUS);
4873     TREEVIEW_Invalidate(infoPtr, infoPtr->selectedItem);
4874     return 0;
4875 }
4876
4877 static LRESULT
4878 TREEVIEW_KillFocus(TREEVIEW_INFO *infoPtr)
4879 {
4880     TRACE("\n");
4881
4882     TREEVIEW_SendSimpleNotify(infoPtr, NM_KILLFOCUS);
4883     TREEVIEW_Invalidate(infoPtr, infoPtr->selectedItem);
4884     return 0;
4885 }
4886
4887
4888 static LRESULT WINAPI
4889 TREEVIEW_WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
4890 {
4891     TREEVIEW_INFO *infoPtr = TREEVIEW_GetInfoPtr(hwnd);
4892     if (infoPtr) TREEVIEW_VerifyTree(infoPtr);
4893     else
4894     {
4895         if (uMsg == WM_CREATE)
4896             TREEVIEW_Create(hwnd);
4897         else
4898             goto def;
4899     }
4900
4901     switch (uMsg)
4902     {
4903     case TVM_CREATEDRAGIMAGE:
4904         return TREEVIEW_CreateDragImage(infoPtr, wParam, lParam);
4905
4906     case TVM_DELETEITEM:
4907         return TREEVIEW_DeleteItem(infoPtr, (HTREEITEM)lParam);
4908
4909     case TVM_EDITLABELA:
4910         return TREEVIEW_EditLabelA(infoPtr, (HTREEITEM)lParam);
4911
4912     case TVM_EDITLABELW:
4913         FIXME("Unimplemented msg TVM_EDITLABELW\n");
4914         return 0;
4915
4916     case TVM_ENDEDITLABELNOW:
4917         return TREEVIEW_EndEditLabelNow(infoPtr, (BOOL)wParam);
4918
4919     case TVM_ENSUREVISIBLE:
4920         return TREEVIEW_EnsureVisible(infoPtr, (HTREEITEM)lParam, TRUE);
4921
4922     case TVM_EXPAND:
4923         return TREEVIEW_ExpandMsg(infoPtr, (UINT)wParam, (HTREEITEM)lParam);
4924
4925     case TVM_GETBKCOLOR:
4926         return TREEVIEW_GetBkColor(infoPtr);
4927
4928     case TVM_GETCOUNT:
4929         return TREEVIEW_GetCount(infoPtr);
4930
4931     case TVM_GETEDITCONTROL:
4932         return TREEVIEW_GetEditControl(infoPtr);
4933
4934     case TVM_GETIMAGELIST:
4935         return TREEVIEW_GetImageList(infoPtr, wParam);
4936
4937     case TVM_GETINDENT:
4938         return TREEVIEW_GetIndent(infoPtr);
4939
4940     case TVM_GETINSERTMARKCOLOR:
4941         return TREEVIEW_GetInsertMarkColor(infoPtr);
4942
4943     case TVM_GETISEARCHSTRINGA:
4944         FIXME("Unimplemented msg TVM_GETISEARCHSTRINGA\n");
4945         return 0;
4946
4947     case TVM_GETISEARCHSTRINGW:
4948         FIXME("Unimplemented msg TVM_GETISEARCHSTRINGW\n");
4949         return 0;
4950
4951     case TVM_GETITEMA:
4952         return TREEVIEW_GetItemA(infoPtr, (LPTVITEMEXA)lParam);
4953
4954     case TVM_GETITEMW:
4955         return TREEVIEW_GetItemW(infoPtr, (LPTVITEMEXA)lParam);
4956
4957     case TVM_GETITEMHEIGHT:
4958         return TREEVIEW_GetItemHeight(infoPtr);
4959
4960     case TVM_GETITEMRECT:
4961         return TREEVIEW_GetItemRect(infoPtr, (BOOL)wParam, (LPRECT)lParam);
4962
4963     case TVM_GETITEMSTATE:
4964         return TREEVIEW_GetItemState(infoPtr, (HTREEITEM)wParam, (UINT)lParam);
4965
4966     case TVM_GETLINECOLOR:
4967         return TREEVIEW_GetLineColor(infoPtr);
4968
4969     case TVM_GETNEXTITEM:
4970         return TREEVIEW_GetNextItem(infoPtr, (UINT)wParam, (HTREEITEM)lParam);
4971
4972     case TVM_GETSCROLLTIME:
4973         return TREEVIEW_GetScrollTime(infoPtr);
4974
4975     case TVM_GETTEXTCOLOR:
4976         return TREEVIEW_GetTextColor(infoPtr);
4977
4978     case TVM_GETTOOLTIPS:
4979         return TREEVIEW_GetToolTips(infoPtr);
4980
4981     case TVM_GETUNICODEFORMAT:
4982         FIXME("Unimplemented msg TVM_GETUNICODEFORMAT\n");
4983         return 0;
4984
4985     case TVM_GETVISIBLECOUNT:
4986         return TREEVIEW_GetVisibleCount(infoPtr);
4987
4988     case TVM_HITTEST:
4989         return TREEVIEW_HitTest(infoPtr, (LPTVHITTESTINFO)lParam);
4990
4991     case TVM_INSERTITEMA:
4992         return TREEVIEW_InsertItemA(infoPtr, lParam);
4993
4994     case TVM_INSERTITEMW:
4995         return TREEVIEW_InsertItemW(infoPtr, lParam);
4996
4997     case TVM_SELECTITEM:
4998         return TREEVIEW_SelectItem(infoPtr, (INT)wParam, (HTREEITEM)lParam);
4999
5000     case TVM_SETBKCOLOR:
5001         return TREEVIEW_SetBkColor(infoPtr, (COLORREF)lParam);
5002
5003     case TVM_SETIMAGELIST:
5004         return TREEVIEW_SetImageList(infoPtr, wParam, (HIMAGELIST)lParam);
5005
5006     case TVM_SETINDENT:
5007         return TREEVIEW_SetIndent(infoPtr, (UINT)wParam);
5008
5009     case TVM_SETINSERTMARK:
5010         return TREEVIEW_SetInsertMark(infoPtr, (BOOL)wParam, (HTREEITEM)lParam);
5011
5012     case TVM_SETINSERTMARKCOLOR:
5013         return TREEVIEW_SetInsertMarkColor(infoPtr, (COLORREF)lParam);
5014
5015     case TVM_SETITEMA:
5016         return TREEVIEW_SetItemA(infoPtr, (LPTVITEMEXA)lParam);
5017
5018     case TVM_SETITEMW:
5019         FIXME("Unimplemented msg TVM_SETITEMW\n");
5020         return 0;
5021
5022     case TVM_SETLINECOLOR:
5023         return TREEVIEW_SetLineColor(infoPtr, (COLORREF)lParam);
5024
5025     case TVM_SETITEMHEIGHT:
5026         return TREEVIEW_SetItemHeight(infoPtr, (INT)(SHORT)wParam);
5027
5028     case TVM_SETSCROLLTIME:
5029         return TREEVIEW_SetScrollTime(infoPtr, (UINT)wParam);
5030
5031     case TVM_SETTEXTCOLOR:
5032         return TREEVIEW_SetTextColor(infoPtr, (COLORREF)lParam);
5033
5034     case TVM_SETTOOLTIPS:
5035         return TREEVIEW_SetToolTips(infoPtr, (HWND)wParam);
5036
5037     case TVM_SETUNICODEFORMAT:
5038         FIXME("Unimplemented msg TVM_SETUNICODEFORMAT\n");
5039         return 0;
5040
5041     case TVM_SORTCHILDREN:
5042         return TREEVIEW_SortChildren(infoPtr, wParam, lParam);
5043
5044     case TVM_SORTCHILDRENCB:
5045         return TREEVIEW_SortChildrenCB(infoPtr, wParam, (LPTVSORTCB)lParam);
5046
5047     case WM_CHAR:
5048         return TREEVIEW_ProcessLetterKeys( hwnd, wParam, lParam );
5049
5050     case WM_COMMAND:
5051         return TREEVIEW_Command(infoPtr, wParam, lParam);
5052
5053     case WM_DESTROY:
5054         return TREEVIEW_Destroy(infoPtr);
5055
5056         /* WM_ENABLE */
5057
5058     case WM_ERASEBKGND:
5059         return TREEVIEW_EraseBackground(infoPtr, (HDC)wParam);
5060
5061     case WM_GETDLGCODE:
5062         return DLGC_WANTARROWS | DLGC_WANTCHARS;
5063
5064     case WM_GETFONT:
5065         return TREEVIEW_GetFont(infoPtr);
5066
5067     case WM_HSCROLL:
5068         return TREEVIEW_HScroll(infoPtr, wParam);
5069
5070     case WM_KEYDOWN:
5071         return TREEVIEW_KeyDown(infoPtr, wParam);
5072
5073     case WM_KILLFOCUS:
5074         return TREEVIEW_KillFocus(infoPtr);
5075
5076     case WM_LBUTTONDBLCLK:
5077         return TREEVIEW_LButtonDoubleClick(infoPtr, lParam);
5078
5079     case WM_LBUTTONDOWN:
5080         return TREEVIEW_LButtonDown(infoPtr, lParam);
5081
5082         /* WM_MBUTTONDOWN */
5083
5084         /* WM_MOUSEMOVE */
5085
5086         /* WM_NOTIFY */
5087
5088         /* WM_NOTIFYFORMAT */
5089
5090     case WM_PAINT:
5091         return TREEVIEW_Paint(infoPtr, wParam);
5092
5093         /* WM_PRINTCLIENT */
5094
5095     case WM_RBUTTONDOWN:
5096         return TREEVIEW_RButtonDown(infoPtr, lParam);
5097
5098     case WM_SETFOCUS:
5099         return TREEVIEW_SetFocus(infoPtr);
5100
5101     case WM_SETFONT:
5102         return TREEVIEW_SetFont(infoPtr, (HFONT)wParam, (BOOL)lParam);
5103
5104     case WM_SETREDRAW:
5105         return TREEVIEW_SetRedraw(infoPtr, wParam, lParam);
5106
5107     case WM_SIZE:
5108         return TREEVIEW_Size(infoPtr, wParam, lParam);
5109
5110     case WM_STYLECHANGED:
5111         return TREEVIEW_StyleChanged(infoPtr, wParam, lParam);
5112
5113         /* WM_SYSCOLORCHANGE */
5114
5115         /* WM_SYSKEYDOWN */
5116
5117     case WM_TIMER:
5118         return TREEVIEW_HandleTimer(infoPtr, wParam);
5119
5120     case WM_VSCROLL:
5121         return TREEVIEW_VScroll(infoPtr, wParam);
5122
5123         /* WM_WININICHANGE */
5124
5125     case WM_MOUSEWHEEL:
5126         if (wParam & (MK_SHIFT | MK_CONTROL))
5127             goto def;
5128         return TREEVIEW_MouseWheel(infoPtr, wParam);
5129
5130     case WM_DRAWITEM:
5131         TRACE("drawItem\n");
5132         goto def;
5133
5134     default:
5135         /* This mostly catches MFC and Delphi messages. :( */
5136         if (uMsg >= WM_USER)
5137             TRACE("Unknown msg %04x wp=%08x lp=%08lx\n", uMsg, wParam, lParam);
5138 def:
5139         return DefWindowProcA(hwnd, uMsg, wParam, lParam);
5140     }
5141     return 0;
5142 }
5143
5144
5145 /* Class Registration ***************************************************/
5146
5147 VOID
5148 TREEVIEW_Register(void)
5149 {
5150     WNDCLASSA wndClass;
5151
5152     TRACE("\n");
5153
5154     ZeroMemory(&wndClass, sizeof(WNDCLASSA));
5155     wndClass.style = CS_GLOBALCLASS | CS_DBLCLKS;
5156     wndClass.lpfnWndProc = (WNDPROC)TREEVIEW_WindowProc;
5157     wndClass.cbClsExtra = 0;
5158     wndClass.cbWndExtra = sizeof(TREEVIEW_INFO *);
5159
5160     wndClass.hCursor = LoadCursorA(0, IDC_ARROWA);
5161     wndClass.hbrBackground = 0;
5162     wndClass.lpszClassName = WC_TREEVIEWA;
5163
5164     RegisterClassA(&wndClass);
5165 }
5166
5167
5168 VOID
5169 TREEVIEW_Unregister(void)
5170 {
5171     UnregisterClassA(WC_TREEVIEWA, (HINSTANCE) NULL);
5172 }
5173
5174
5175 /* Tree Verification ****************************************************/
5176
5177 #ifdef NDEBUG
5178 static inline void
5179 TREEVIEW_VerifyChildren(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *item);
5180
5181 static inline void TREEVIEW_VerifyItemCommon(TREEVIEW_INFO *infoPtr,
5182                                              TREEVIEW_ITEM *item)
5183 {
5184     assert(infoPtr != NULL);
5185     assert(item != NULL);
5186
5187     /* both NULL, or both non-null */
5188     assert((item->firstChild == NULL) == (item->lastChild == NULL));
5189
5190     assert(item->firstChild != item);
5191     assert(item->lastChild != item);
5192
5193     if (item->firstChild)
5194     {
5195         assert(item->firstChild->parent == item);
5196         assert(item->firstChild->prevSibling == NULL);
5197     }
5198
5199     if (item->lastChild)
5200     {
5201         assert(item->lastChild->parent == item);
5202         assert(item->lastChild->nextSibling == NULL);
5203     }
5204
5205     assert(item->nextSibling != item);
5206     if (item->nextSibling)
5207     {
5208         assert(item->nextSibling->parent == item->parent);
5209         assert(item->nextSibling->prevSibling == item);
5210     }
5211
5212     assert(item->prevSibling != item);
5213     if (item->prevSibling)
5214     {
5215         assert(item->prevSibling->parent == item->parent);
5216         assert(item->prevSibling->nextSibling == item);
5217     }
5218 }
5219
5220 static inline void
5221 TREEVIEW_VerifyItem(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *item)
5222 {
5223     assert(item != NULL);
5224
5225     assert(item->parent != NULL);
5226     assert(item->parent != item);
5227     assert(item->iLevel == item->parent->iLevel + 1);
5228
5229     assert(DPA_GetPtrIndex(infoPtr->items, item) != -1);
5230
5231     TREEVIEW_VerifyItemCommon(infoPtr, item);
5232
5233     TREEVIEW_VerifyChildren(infoPtr, item);
5234 }
5235
5236 static inline void
5237 TREEVIEW_VerifyChildren(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *item)
5238 {
5239     TREEVIEW_ITEM *child;
5240     assert(item != NULL);
5241
5242     for (child = item->firstChild; child != NULL; child = child->nextSibling)
5243         TREEVIEW_VerifyItem(infoPtr, child);
5244 }
5245
5246 static inline void
5247 TREEVIEW_VerifyRoot(TREEVIEW_INFO *infoPtr)
5248 {
5249     TREEVIEW_ITEM *root = infoPtr->root;
5250
5251     assert(root != NULL);
5252     assert(root->iLevel == -1);
5253     assert(root->parent == NULL);
5254     assert(root->prevSibling == NULL);
5255
5256     TREEVIEW_VerifyItemCommon(infoPtr, root);
5257
5258     TREEVIEW_VerifyChildren(infoPtr, root);
5259 }
5260
5261 static void
5262 TREEVIEW_VerifyTree(TREEVIEW_INFO *infoPtr)
5263 {
5264     assert(infoPtr != NULL);
5265
5266     TREEVIEW_VerifyRoot(infoPtr);
5267 }
5268 #endif