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