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