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