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