Removed inclusion of wine/winestring.h from winbase.h and added it to
[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;
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         TREEVIEW_InsertBefore(newItem, parentItem->firstChild, parentItem);
1056         if (infoPtr->firstVisible == parentItem->firstChild)
1057             TREEVIEW_SetFirstVisible(infoPtr, newItem, TRUE);
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 as 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 comparision 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     return max(16, tm.tmHeight + tm.tmExternalLeading);
1574 }
1575
1576 static LRESULT
1577 TREEVIEW_SetItemHeight(TREEVIEW_INFO *infoPtr, INT newHeight)
1578 {
1579     INT prevHeight = infoPtr->uItemHeight;
1580
1581     TRACE("%d \n", newHeight);
1582     if (newHeight == -1)
1583     {
1584         infoPtr->uItemHeight = TREEVIEW_NaturalHeight(infoPtr);
1585         infoPtr->bHeightSet = FALSE;
1586     }
1587     else
1588     {
1589         infoPtr->uItemHeight = newHeight;
1590         infoPtr->bHeightSet = TRUE;
1591     }
1592
1593     /* Round down, unless we support odd ("non even") heights. */
1594     if (!(infoPtr->dwStyle) & TVS_NONEVENHEIGHT)
1595         infoPtr->uItemHeight &= ~1;
1596
1597     if (infoPtr->uItemHeight != prevHeight)
1598     {
1599         TREEVIEW_RecalculateVisibleOrder(infoPtr, NULL);
1600         TREEVIEW_UpdateScrollBars(infoPtr);
1601         TREEVIEW_QueueRefresh(infoPtr);
1602     }
1603
1604     return prevHeight;
1605 }
1606
1607 static LRESULT
1608 TREEVIEW_GetItemHeight(TREEVIEW_INFO *infoPtr)
1609 {
1610     TRACE("\n");
1611     return infoPtr->uItemHeight;
1612 }
1613
1614
1615 static LRESULT
1616 TREEVIEW_GetFont(TREEVIEW_INFO *infoPtr)
1617 {
1618     TRACE("%x\n", infoPtr->hFont);
1619     return infoPtr->hFont;
1620 }
1621
1622
1623 static INT CALLBACK
1624 TREEVIEW_ResetTextWidth(LPVOID pItem, DWORD unused)
1625 {
1626     (void)unused;
1627
1628     ((TREEVIEW_ITEM *)pItem)->textWidth = 0;
1629
1630     return 1;
1631 }
1632
1633 static LRESULT
1634 TREEVIEW_SetFont(TREEVIEW_INFO *infoPtr, HFONT hFont, BOOL bRedraw)
1635 {
1636     UINT uHeight = infoPtr->uItemHeight;
1637
1638     TRACE("%x %i\n", hFont, bRedraw);
1639
1640     infoPtr->hFont = hFont ? hFont : GetStockObject(SYSTEM_FONT);
1641
1642     DeleteObject(infoPtr->hBoldFont);
1643     infoPtr->hBoldFont = TREEVIEW_CreateBoldFont(infoPtr->hFont);
1644
1645     if (!infoPtr->bHeightSet)
1646         infoPtr->uItemHeight = TREEVIEW_NaturalHeight(infoPtr);
1647
1648     if (uHeight != infoPtr->uItemHeight)
1649        TREEVIEW_RecalculateVisibleOrder(infoPtr, NULL);
1650
1651     DPA_EnumCallback(infoPtr->items, TREEVIEW_ResetTextWidth, 0);
1652
1653     TREEVIEW_UpdateSubTree(infoPtr, infoPtr->root);
1654     TREEVIEW_UpdateScrollBars(infoPtr);
1655
1656     if (bRedraw)
1657         TREEVIEW_QueueRefresh(infoPtr);
1658
1659     return 0;
1660 }
1661
1662
1663 static LRESULT
1664 TREEVIEW_GetLineColor(TREEVIEW_INFO *infoPtr)
1665 {
1666     TRACE("\n");
1667     return (LRESULT)infoPtr->clrLine;
1668 }
1669
1670 static LRESULT
1671 TREEVIEW_SetLineColor(TREEVIEW_INFO *infoPtr, COLORREF color)
1672 {
1673     COLORREF prevColor = infoPtr->clrLine;
1674
1675     TRACE("\n");
1676     infoPtr->clrLine = color;
1677     return (LRESULT)prevColor;
1678 }
1679
1680
1681 static LRESULT
1682 TREEVIEW_GetTextColor(TREEVIEW_INFO *infoPtr)
1683 {
1684     TRACE("\n");
1685     return (LRESULT)infoPtr->clrText;
1686 }
1687
1688 static LRESULT
1689 TREEVIEW_SetTextColor(TREEVIEW_INFO *infoPtr, COLORREF color)
1690 {
1691     COLORREF prevColor = infoPtr->clrText;
1692
1693     TRACE("\n");
1694     infoPtr->clrText = color;
1695
1696     if (infoPtr->clrText != prevColor)
1697         TREEVIEW_QueueRefresh(infoPtr);
1698
1699     return (LRESULT)prevColor;
1700 }
1701
1702
1703 static LRESULT
1704 TREEVIEW_GetBkColor(TREEVIEW_INFO *infoPtr)
1705 {
1706     TRACE("\n");
1707     return (LRESULT)infoPtr->clrBk;
1708 }
1709
1710 static LRESULT
1711 TREEVIEW_SetBkColor(TREEVIEW_INFO *infoPtr, COLORREF newColor)
1712 {
1713     COLORREF prevColor = infoPtr->clrBk;
1714
1715     TRACE("\n");
1716     infoPtr->clrBk = newColor;
1717
1718     if (newColor != prevColor)
1719         TREEVIEW_QueueRefresh(infoPtr);
1720
1721     return (LRESULT)prevColor;
1722 }
1723
1724
1725 static LRESULT
1726 TREEVIEW_GetInsertMarkColor(TREEVIEW_INFO *infoPtr)
1727 {
1728     TRACE("\n");
1729     return (LRESULT)infoPtr->clrInsertMark;
1730 }
1731
1732 static LRESULT
1733 TREEVIEW_SetInsertMarkColor(TREEVIEW_INFO *infoPtr, COLORREF color)
1734 {
1735     COLORREF prevColor = infoPtr->clrInsertMark;
1736
1737     TRACE("%lx\n", color);
1738     infoPtr->clrInsertMark = color;
1739
1740     return (LRESULT)prevColor;
1741 }
1742
1743
1744 static LRESULT
1745 TREEVIEW_SetInsertMark(TREEVIEW_INFO *infoPtr, BOOL wParam, HTREEITEM item)
1746 {
1747     TRACE("%d %p\n", wParam, item);
1748
1749     if (!TREEVIEW_ValidItem(infoPtr, item))
1750         return 0;
1751
1752     infoPtr->insertBeforeorAfter = wParam;
1753     infoPtr->insertMarkItem = item;
1754
1755     TREEVIEW_QueueRefresh(infoPtr);
1756
1757     return 1;
1758 }
1759
1760
1761 /************************************************************************
1762  * Some serious braindamage here. lParam is a pointer to both the
1763  * input HTREEITEM and the output RECT.
1764  */
1765 static LRESULT
1766 TREEVIEW_GetItemRect(TREEVIEW_INFO *infoPtr, BOOL fTextRect, LPRECT lpRect)
1767 {
1768     TREEVIEW_ITEM *wineItem;
1769     const HTREEITEM *pItem = (HTREEITEM *)lpRect;
1770
1771     TRACE("\n");
1772     /*
1773      * validate parameters
1774      */
1775     if (pItem == NULL)
1776         return FALSE;
1777
1778     wineItem = *pItem;
1779     if (!TREEVIEW_ValidItem(infoPtr, wineItem) || !ISVISIBLE(wineItem))
1780         return FALSE;
1781
1782     /* 
1783      * If wParam is TRUE return the text size otherwise return 
1784      * the whole item size        
1785      */
1786     if (fTextRect)
1787     {
1788         /* Windows does not send TVN_GETDISPINFO here. */
1789
1790         lpRect->top = wineItem->rect.top;
1791         lpRect->bottom = wineItem->rect.bottom;
1792
1793         lpRect->left = wineItem->textOffset;
1794         lpRect->right = wineItem->textOffset + wineItem->textWidth;
1795     }
1796     else
1797     {
1798         *lpRect = wineItem->rect;
1799     }
1800
1801     TRACE("%s [L:%d R:%d T:%d B:%d]\n", fTextRect ? "text" : "item",
1802           lpRect->left, lpRect->right, lpRect->top, lpRect->bottom);
1803
1804     return TRUE;
1805 }
1806
1807 static inline LRESULT
1808 TREEVIEW_GetVisibleCount(TREEVIEW_INFO *infoPtr)
1809 {
1810     /* Suprise! This does not take integral height into account. */
1811     return infoPtr->clientHeight / infoPtr->uItemHeight;
1812 }
1813
1814
1815 static LRESULT
1816 TREEVIEW_GetItemA(TREEVIEW_INFO *infoPtr, LPTVITEMEXA tvItem)
1817 {
1818     TREEVIEW_ITEM *wineItem;
1819
1820     wineItem = tvItem->hItem;
1821     if (!TREEVIEW_ValidItem(infoPtr, wineItem))
1822         return FALSE;
1823
1824     TREEVIEW_UpdateDispInfo(infoPtr, wineItem, tvItem->mask);
1825
1826     if (tvItem->mask & TVIF_CHILDREN)
1827         tvItem->cChildren = wineItem->cChildren;
1828
1829     if (tvItem->mask & TVIF_HANDLE)
1830         tvItem->hItem = wineItem;
1831
1832     if (tvItem->mask & TVIF_IMAGE)
1833         tvItem->iImage = wineItem->iImage;
1834
1835     if (tvItem->mask & TVIF_INTEGRAL)
1836         tvItem->iIntegral = wineItem->iIntegral;
1837
1838     /* undocumented: windows ignores TVIF_PARAM and
1839      * * always sets lParam
1840      */
1841     tvItem->lParam = wineItem->lParam;
1842
1843     if (tvItem->mask & TVIF_SELECTEDIMAGE)
1844         tvItem->iSelectedImage = wineItem->iSelectedImage;
1845
1846     if (tvItem->mask & TVIF_STATE)
1847         tvItem->state = wineItem->state & tvItem->stateMask;
1848
1849     if (tvItem->mask & TVIF_TEXT)
1850         lstrcpynA(tvItem->pszText, wineItem->pszText, tvItem->cchTextMax);
1851
1852     TRACE("item <%p>, txt %p, img %p, mask %x\n",
1853           wineItem, tvItem->pszText, &tvItem->iImage, tvItem->mask);
1854
1855     return TRUE;
1856 }
1857
1858 /* Beware MSDN Library Visual Studio 6.0. It says -1 on failure, 0 on success,
1859  * which is wrong. */
1860 static LRESULT
1861 TREEVIEW_SetItemA(TREEVIEW_INFO *infoPtr, LPTVITEMEXA tvItem)
1862 {
1863     TREEVIEW_ITEM *wineItem;
1864     TREEVIEW_ITEM originalItem;
1865
1866     wineItem = tvItem->hItem;
1867
1868     TRACE("item %d,mask %x\n", TREEVIEW_GetItemIndex(infoPtr, wineItem),
1869           tvItem->mask);
1870
1871     if (!TREEVIEW_ValidItem(infoPtr, wineItem))
1872         return FALSE;
1873
1874     if (!TREEVIEW_DoSetItem(infoPtr, wineItem, tvItem))
1875         return FALSE;
1876
1877     /* store the orignal item values */
1878     originalItem = *wineItem;
1879
1880     /* If the text or TVIS_BOLD was changed, and it is visible, recalculate. */
1881     if ((tvItem->mask & TVIF_TEXT
1882          || (tvItem->mask & TVIF_STATE && tvItem->stateMask & TVIS_BOLD))
1883         && ISVISIBLE(wineItem))
1884     {
1885         TREEVIEW_UpdateDispInfo(infoPtr, wineItem, TVIF_TEXT);
1886         TREEVIEW_ComputeTextWidth(infoPtr, wineItem, 0);
1887     }
1888
1889     if (tvItem->mask != 0 && ISVISIBLE(wineItem))
1890     {
1891         /* The refresh updates everything, but we can't wait until then. */
1892         TREEVIEW_ComputeItemInternalMetrics(infoPtr, wineItem);
1893
1894         /* if any of the items values changed, redraw the item */
1895         if(memcmp(&originalItem, wineItem, sizeof(TREEVIEW_ITEM)))
1896         {
1897             if (tvItem->mask & TVIF_INTEGRAL)
1898             {
1899                 TREEVIEW_RecalculateVisibleOrder(infoPtr, wineItem);
1900                 TREEVIEW_UpdateScrollBars(infoPtr);
1901
1902                 TREEVIEW_QueueRefresh(infoPtr);
1903             }
1904             else
1905             {
1906                 TREEVIEW_UpdateScrollBars(infoPtr);
1907                 TREEVIEW_QueueItemRefresh(infoPtr, wineItem);
1908             }
1909         }
1910     }
1911
1912     return TRUE;
1913 }
1914
1915 static LRESULT
1916 TREEVIEW_GetItemW(TREEVIEW_INFO *infoPtr, LPTVITEMEXA tvItem)
1917 {
1918     TREEVIEW_ITEM *wineItem;
1919     INT         iItem;
1920     iItem = (INT)tvItem->hItem;
1921
1922     wineItem = tvItem->hItem;
1923     if(!TREEVIEW_ValidItem (infoPtr, wineItem))
1924         return FALSE;
1925
1926     TREEVIEW_UpdateDispInfo(infoPtr, wineItem, tvItem->mask);
1927
1928     if (tvItem->mask & TVIF_CHILDREN) {
1929         if (TVIF_CHILDREN==I_CHILDRENCALLBACK)
1930             FIXME("I_CHILDRENCALLBACK not supported\n");
1931         tvItem->cChildren = wineItem->cChildren;
1932     }
1933
1934     if (tvItem->mask & TVIF_HANDLE) {
1935         tvItem->hItem = wineItem;
1936     }
1937     if (tvItem->mask & TVIF_IMAGE) {
1938         tvItem->iImage = wineItem->iImage;
1939     }
1940     if (tvItem->mask & TVIF_INTEGRAL) {
1941         tvItem->iIntegral = wineItem->iIntegral;
1942     }
1943     /* undocumented: windows ignores TVIF_PARAM and
1944      * always sets lParam           */
1945     tvItem->lParam = wineItem->lParam;
1946     if (tvItem->mask & TVIF_SELECTEDIMAGE) {
1947         tvItem->iSelectedImage = wineItem->iSelectedImage;
1948     }
1949     if (tvItem->mask & TVIF_STATE) {
1950         tvItem->state = wineItem->state & tvItem->stateMask;
1951     }
1952 #if 0
1953     if (tvItem->mask & TVIF_TEXT) {
1954         if (wineItem->pszText == LPSTR_TEXTCALLBACKW) {
1955             tvItem->pszText = LPSTR_TEXTCALLBACKW;  /* FIXME:send notification? */
1956             ERR(" GetItem called with LPSTR_TEXTCALLBACK\n");
1957         }
1958         else if (wineItem->pszText) {
1959             lstrcpynAtoW(tvItem->pszText, wineItem->pszText, tvItem->cchTextMax);
1960         }
1961     }
1962 #endif
1963     wineItem->pszText = NULL;
1964     TRACE("item %d<%p>, txt %p, img %p, action %x\n",
1965         iItem, tvItem, tvItem->pszText, &tvItem->iImage, tvItem->mask);
1966     return TRUE;
1967 }
1968
1969 static LRESULT
1970 TREEVIEW_GetItemState(TREEVIEW_INFO *infoPtr, HTREEITEM wineItem, UINT mask)
1971 {
1972     TRACE("\n");
1973
1974     if (!wineItem || !TREEVIEW_ValidItem(infoPtr, wineItem))
1975         return 0;
1976
1977     return (wineItem->state & mask);
1978 }
1979
1980 static LRESULT
1981 TREEVIEW_GetNextItem(TREEVIEW_INFO *infoPtr, UINT which, HTREEITEM wineItem)
1982 {
1983     TREEVIEW_ITEM *retval;
1984
1985     retval = 0;
1986
1987     /* handle all the global data here */
1988     switch (which)
1989     {
1990     case TVGN_CHILD:            /* Special case: child of 0 is root */
1991         if (wineItem)
1992             break;
1993         /* fall through */
1994     case TVGN_ROOT:
1995         retval = infoPtr->root->firstChild;
1996         break;
1997
1998     case TVGN_CARET:
1999         retval = infoPtr->selectedItem;
2000         break;
2001
2002     case TVGN_FIRSTVISIBLE:
2003         retval = infoPtr->firstVisible;
2004         break;
2005
2006     case TVGN_DROPHILITE:
2007         retval = infoPtr->dropItem;
2008         break;
2009
2010     case TVGN_LASTVISIBLE:
2011         retval = TREEVIEW_GetLastListItem(infoPtr, infoPtr->root);
2012         break;
2013     }
2014
2015     if (retval)
2016     {
2017         TRACE("flags:%x, returns %p\n", which, retval);
2018         return (LRESULT)retval;
2019     }
2020
2021     if (!TREEVIEW_ValidItem(infoPtr, wineItem))
2022         return FALSE;
2023
2024     switch (which)
2025     {
2026     case TVGN_NEXT:
2027         retval = wineItem->nextSibling;
2028         break;
2029     case TVGN_PREVIOUS:
2030         retval = wineItem->prevSibling;
2031         break;
2032     case TVGN_PARENT:
2033         retval = (wineItem->parent != infoPtr->root) ? wineItem->parent : NULL;
2034         break;
2035     case TVGN_CHILD:
2036         retval = wineItem->firstChild;
2037         break;
2038     case TVGN_NEXTVISIBLE:
2039         retval = TREEVIEW_GetNextListItem(infoPtr, wineItem);
2040         break;
2041     case TVGN_PREVIOUSVISIBLE:
2042         retval = TREEVIEW_GetPrevListItem(infoPtr, wineItem);
2043         break;
2044     default:
2045         TRACE("Unknown msg %x,item %p\n", which, wineItem);
2046         break;
2047     }
2048
2049     TRACE("flags:%x, item %p;returns %p\n", which, wineItem, retval);
2050     return (LRESULT)retval;
2051 }
2052
2053
2054 static LRESULT
2055 TREEVIEW_GetCount(TREEVIEW_INFO *infoPtr)
2056 {
2057     TRACE(" %d\n", infoPtr->uNumItems);
2058     return (LRESULT)infoPtr->uNumItems;
2059 }
2060
2061 static VOID
2062 TREEVIEW_ToggleItemState(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *item)
2063 {
2064     if (infoPtr->dwStyle & TVS_CHECKBOXES)
2065     {
2066         static const unsigned int state_table[] = { 0, 2, 1 };
2067
2068         unsigned int state;
2069
2070         state = STATEIMAGEINDEX(item->state);
2071         TRACE("state:%x\n", state);
2072         item->state &= ~TVIS_STATEIMAGEMASK;
2073
2074         if (state < 3)
2075             state = state_table[state];
2076
2077         item->state |= INDEXTOSTATEIMAGEMASK(state);
2078
2079         TRACE("state:%x\n", state);
2080         TREEVIEW_QueueItemRefresh(infoPtr, item);
2081     }
2082 }
2083
2084
2085 /* Painting *************************************************************/
2086
2087 /* Draw the lines and expand button for an item. Also draws one section
2088  * of the line from item's parent to item's parent's next sibling. */
2089 static void
2090 TREEVIEW_DrawItemLines(TREEVIEW_INFO *infoPtr, HDC hdc, TREEVIEW_ITEM *item)
2091 {
2092     LONG centerx, centery;
2093     BOOL lar = ((infoPtr->dwStyle
2094                  & (TVS_LINESATROOT|TVS_HASLINES|TVS_HASBUTTONS))
2095                 > TVS_LINESATROOT);
2096
2097     if (!lar && item->iLevel == 0)
2098         return;
2099
2100     centerx = (item->linesOffset + item->stateOffset) / 2;
2101     centery = (item->rect.top + item->rect.bottom) / 2;
2102
2103     if (infoPtr->dwStyle & TVS_HASLINES)
2104     {
2105         HPEN hOldPen, hNewPen;
2106         HTREEITEM parent;
2107
2108         /* 
2109          * Get a dotted grey pen
2110          */
2111         hNewPen = CreatePen(PS_DOT, 0, infoPtr->clrLine);
2112         hOldPen = SelectObject(hdc, hNewPen);
2113
2114         MoveToEx(hdc, item->stateOffset, centery, NULL);
2115         LineTo(hdc, centerx - 1, centery);
2116
2117         if (item->prevSibling || item->parent != infoPtr->root)
2118         {
2119             MoveToEx(hdc, centerx, item->rect.top, NULL);
2120             LineTo(hdc, centerx, centery);
2121         }
2122
2123         if (item->nextSibling)
2124         {
2125             MoveToEx(hdc, centerx, centery, NULL);
2126             LineTo(hdc, centerx, item->rect.bottom + 1);
2127         }
2128
2129         /* Draw the line from our parent to its next sibling. */
2130         parent = item->parent;
2131         while (parent != infoPtr->root)
2132         {
2133             int pcenterx = (parent->linesOffset + parent->stateOffset) / 2;
2134
2135             if (parent->nextSibling
2136                 /* skip top-levels unless TVS_LINESATROOT */
2137                 && parent->stateOffset > parent->linesOffset)
2138             {
2139                 MoveToEx(hdc, pcenterx, item->rect.top, NULL);
2140                 LineTo(hdc, pcenterx, item->rect.bottom + 1);
2141             }
2142
2143             parent = parent->parent;
2144         }
2145
2146         SelectObject(hdc, hOldPen);
2147         DeleteObject(hNewPen);
2148     }
2149
2150     /* 
2151      * Display the (+/-) signs
2152      */
2153
2154     if (infoPtr->dwStyle & TVS_HASBUTTONS)
2155     {
2156         if (item->cChildren)
2157         {
2158             LONG height = item->rect.bottom - item->rect.top;
2159             LONG width  = item->stateOffset - item->linesOffset;
2160             LONG rectsize = min(height, width) / 4;
2161             /* plussize = ceil(rectsize * 3/4) */
2162             LONG plussize = (rectsize + 1) * 3 / 4;
2163
2164             HPEN hNewPen  = CreatePen(PS_SOLID, 0, infoPtr->clrLine);
2165             HPEN hOldPen  = SelectObject(hdc, hNewPen);
2166             HBRUSH hbr    = CreateSolidBrush(infoPtr->clrBk);
2167             HBRUSH hbrOld = SelectObject(hdc, hbr);
2168
2169             Rectangle(hdc, centerx - rectsize, centery - rectsize,
2170                       centerx + rectsize + 1, centery + rectsize + 1);
2171
2172             SelectObject(hdc, hbrOld);
2173             DeleteObject(hbr);
2174
2175             SelectObject(hdc, hOldPen);
2176             DeleteObject(hNewPen);
2177
2178             MoveToEx(hdc, centerx - plussize + 1, centery, NULL);
2179             LineTo(hdc, centerx + plussize, centery);
2180
2181             if (!(item->state & TVIS_EXPANDED))
2182             {
2183                 MoveToEx(hdc, centerx, centery - plussize + 1, NULL);
2184                 LineTo(hdc, centerx, centery + plussize);
2185             }
2186         }
2187     }
2188 }
2189
2190 static void
2191 TREEVIEW_DrawItem(TREEVIEW_INFO *infoPtr, HDC hdc, TREEVIEW_ITEM *wineItem)
2192 {
2193     INT cditem;
2194     HFONT hOldFont;
2195     int centery;
2196
2197     hOldFont = SelectObject(hdc, TREEVIEW_FontForItem(infoPtr, wineItem));
2198
2199     TREEVIEW_UpdateDispInfo(infoPtr, wineItem, CALLBACK_MASK_ALL);
2200
2201     /* The custom draw handler can query the text rectangle,
2202      * so get ready. */
2203     TREEVIEW_ComputeTextWidth(infoPtr, wineItem, hdc);
2204
2205     cditem = 0;
2206
2207     if (infoPtr->cdmode & CDRF_NOTIFYITEMDRAW)
2208     {
2209         cditem = TREEVIEW_SendCustomDrawItemNotify
2210             (infoPtr, hdc, wineItem, CDDS_ITEMPREPAINT);
2211         TRACE("prepaint:cditem-app returns 0x%x\n", cditem);
2212
2213         if (cditem & CDRF_SKIPDEFAULT)
2214         {
2215             SelectObject(hdc, hOldFont);
2216             return;
2217         }
2218     }
2219
2220     if (cditem & CDRF_NEWFONT)
2221         TREEVIEW_ComputeTextWidth(infoPtr, wineItem, hdc);
2222
2223     TREEVIEW_DrawItemLines(infoPtr, hdc, wineItem);
2224
2225     centery = (wineItem->rect.top + wineItem->rect.bottom) / 2;
2226
2227     /* 
2228      * Display the images associated with this item
2229      */
2230     {
2231         INT imageIndex;
2232
2233         /* State images are displayed to the left of the Normal image
2234          * image number is in state; zero should be `display no image'.
2235          */
2236         imageIndex = STATEIMAGEINDEX(wineItem->state);
2237
2238         if (infoPtr->himlState && imageIndex)
2239         {
2240             ImageList_Draw(infoPtr->himlState, imageIndex, hdc,
2241                            wineItem->stateOffset,
2242                            centery - infoPtr->stateImageHeight / 2,
2243                            ILD_NORMAL);
2244         }
2245
2246         /* Now, draw the normal image; can be either selected or
2247          * non-selected image. 
2248          */
2249
2250         if ((wineItem->state & TVIS_SELECTED) && (wineItem->iSelectedImage))
2251         {
2252             /* The item is curently selected */
2253             imageIndex = wineItem->iSelectedImage;
2254         }
2255         else
2256         {
2257             /* The item is not selected */
2258             imageIndex = wineItem->iImage;
2259         }
2260
2261         if (infoPtr->himlNormal)
2262         {
2263             int ovlIdx = wineItem->state & TVIS_OVERLAYMASK;
2264
2265             ImageList_Draw(infoPtr->himlNormal, imageIndex, hdc,
2266                            wineItem->imageOffset,
2267                            centery - infoPtr->normalImageHeight / 2,
2268                            ILD_NORMAL | ovlIdx);
2269         }
2270     }
2271
2272
2273     /* 
2274      * Display the text associated with this item
2275      */
2276
2277     /* Don't paint item's text if it's being edited */
2278     if (!infoPtr->hwndEdit || (infoPtr->selectedItem != wineItem))
2279     {
2280         if (wineItem->pszText)
2281         {
2282             COLORREF oldTextColor = 0;
2283             INT oldBkMode;
2284             HBRUSH hbrBk = 0;
2285             BOOL inFocus = (GetFocus() == infoPtr->hwnd);
2286             RECT rcText;
2287
2288             oldBkMode = SetBkMode(hdc, TRANSPARENT);
2289
2290             /* - If item is drop target or it is selected and window is in focus -
2291              * use blue background (COLOR_HIGHLIGHT).
2292              * - If item is selected, window is not in focus, but it has style
2293              * TVS_SHOWSELALWAYS - use grey background (COLOR_BTNFACE)
2294              * - Otherwise - don't fill background
2295              */
2296             if ((wineItem->state & TVIS_DROPHILITED) || ((wineItem == infoPtr->focusedItem) && !(wineItem->state & TVIS_SELECTED)) ||
2297                 ((wineItem->state & TVIS_SELECTED) && (!infoPtr->focusedItem) &&
2298                  (inFocus || (infoPtr->dwStyle & TVS_SHOWSELALWAYS))))
2299             {
2300                 if ((wineItem->state & TVIS_DROPHILITED) || inFocus)
2301                 {
2302                     hbrBk = CreateSolidBrush(GetSysColor(COLOR_HIGHLIGHT));
2303                     oldTextColor =
2304                         SetTextColor(hdc, GetSysColor(COLOR_HIGHLIGHTTEXT));
2305                 }
2306                 else
2307                 {
2308                     hbrBk = CreateSolidBrush(GetSysColor(COLOR_BTNFACE));
2309
2310                     if (infoPtr->clrText == -1)
2311                         oldTextColor =
2312                             SetTextColor(hdc, GetSysColor(COLOR_WINDOWTEXT));
2313                     else
2314                         oldTextColor = SetTextColor(hdc, infoPtr->clrText);
2315                 }
2316             }
2317             else
2318             {
2319                 if (infoPtr->clrText == -1)
2320                     oldTextColor =
2321                         SetTextColor(hdc, GetSysColor(COLOR_WINDOWTEXT));
2322                 else
2323                     oldTextColor = SetTextColor(hdc, infoPtr->clrText);
2324             }
2325
2326             rcText.top = wineItem->rect.top;
2327             rcText.bottom = wineItem->rect.bottom;
2328             rcText.left = wineItem->textOffset;
2329             rcText.right = rcText.left + wineItem->textWidth + 4;
2330
2331             if (hbrBk)
2332             {
2333                 FillRect(hdc, &rcText, hbrBk);
2334                 DeleteObject(hbrBk);
2335             }
2336
2337             /* Draw the box arround the selected item */
2338             if ((wineItem == infoPtr->selectedItem) && inFocus)
2339             {
2340                 HPEN hNewPen = CreatePen(PS_DOT, 0,
2341                                          GetSysColor(COLOR_WINDOWTEXT));
2342                 HPEN hOldPen = SelectObject(hdc, hNewPen);
2343                 INT rop = SetROP2(hdc, R2_XORPEN);
2344                 POINT points[5];
2345
2346                 points[4].x = points[0].x = rcText.left;
2347                 points[4].y = points[0].y = rcText.top;
2348                 points[1].x = rcText.right - 1;
2349                 points[1].y = rcText.top;
2350                 points[2].x = rcText.right - 1;
2351                 points[2].y = rcText.bottom - 1;
2352                 points[3].x = rcText.left;
2353                 points[3].y = rcText.bottom - 1;
2354
2355                 Polyline(hdc, points, 5);
2356
2357                 SetROP2(hdc, rop);
2358                 SelectObject(hdc, hOldPen);
2359                 DeleteObject(hNewPen);
2360             }
2361
2362             rcText.left += 2;
2363             rcText.right -= 2;
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 Lenght 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 = (LONG)(INT16)LOWORD(msg.lParam);
3530                 pt.y = (LONG)(INT16)HIWORD(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 = (LONG)(INT16)LOWORD(lParam);
3575     hit.pt.y = (LONG)(INT16)HIWORD(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 send 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 = (LONG)(INT16)LOWORD(lParam);
3646     ht.pt.y = (LONG)(INT16)HIWORD(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 focuedItem 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 allow 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 of 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 = (LONG)(INT16)LOWORD(lParam);
3795     ht.pt.y = (LONG)(INT16)HIWORD(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     HWND hwnd = infoPtr->hwnd;
3821     POINT pt = *pPt;
3822
3823     /* Change to screen coordinate for WM_CONTEXTMENU */
3824     ClientToScreen(hwnd, &pt);
3825
3826     SendMessageA(hwnd, WM_CONTEXTMENU, (WPARAM)hwnd, MAKELPARAM(pt.x, pt.y));
3827     return 0;
3828 }
3829
3830
3831 static LRESULT
3832 TREEVIEW_CreateDragImage(TREEVIEW_INFO *infoPtr, WPARAM wParam, LPARAM lParam)
3833 {
3834     TREEVIEW_ITEM *dragItem = (HTREEITEM)lParam;
3835     INT cx, cy;
3836     HDC hdc, htopdc;
3837     HWND hwtop;
3838     HBITMAP hbmp, hOldbmp;
3839     SIZE size;
3840     RECT rc;
3841     HFONT hOldFont;
3842
3843     TRACE("\n");
3844
3845     if (!(infoPtr->himlNormal))
3846         return 0;
3847
3848     if (!dragItem || !TREEVIEW_ValidItem(infoPtr, dragItem))
3849         return 0;
3850
3851     TREEVIEW_UpdateDispInfo(infoPtr, dragItem, TVIF_TEXT);
3852
3853     hwtop = GetDesktopWindow();
3854     htopdc = GetDC(hwtop);
3855     hdc = CreateCompatibleDC(htopdc);
3856
3857     hOldFont = SelectObject(hdc, infoPtr->hFont);
3858     GetTextExtentPoint32A(hdc, dragItem->pszText, lstrlenA(dragItem->pszText),
3859                           &size);
3860     TRACE("%ld %ld %s %d\n", size.cx, size.cy, dragItem->pszText,
3861           lstrlenA(dragItem->pszText));
3862     hbmp = CreateCompatibleBitmap(htopdc, size.cx, size.cy);
3863     hOldbmp = SelectObject(hdc, hbmp);
3864
3865     ImageList_GetIconSize(infoPtr->himlNormal, &cx, &cy);
3866     size.cx += cx;
3867     if (cy > size.cy)
3868         size.cy = cy;
3869
3870     infoPtr->dragList = ImageList_Create(size.cx, size.cy, ILC_COLOR, 10, 10);
3871     ImageList_Draw(infoPtr->himlNormal, dragItem->iImage, hdc, 0, 0,
3872                    ILD_NORMAL);
3873
3874 /*
3875  ImageList_GetImageInfo (infoPtr->himlNormal, dragItem->hItem, &iminfo);
3876  ImageList_AddMasked (infoPtr->dragList, iminfo.hbmImage, CLR_DEFAULT);
3877 */
3878
3879 /* draw item text */
3880
3881     SetRect(&rc, cx, 0, size.cx, size.cy);
3882     DrawTextA(hdc, dragItem->pszText, lstrlenA(dragItem->pszText), &rc,
3883               DT_LEFT);
3884     SelectObject(hdc, hOldFont);
3885     SelectObject(hdc, hOldbmp);
3886
3887     ImageList_Add(infoPtr->dragList, hbmp, 0);
3888
3889     DeleteDC(hdc);
3890     DeleteObject(hbmp);
3891     ReleaseDC(hwtop, htopdc);
3892
3893     return (LRESULT)infoPtr->dragList;
3894 }
3895
3896 /* Selection ************************************************************/
3897
3898 static LRESULT
3899 TREEVIEW_DoSelectItem(TREEVIEW_INFO *infoPtr, INT action, HTREEITEM newSelect,
3900                       INT cause)
3901 {
3902     TREEVIEW_ITEM *prevSelect;
3903     RECT rcFocused;
3904
3905     assert(newSelect == NULL || TREEVIEW_ValidItem(infoPtr, newSelect));
3906
3907     TRACE("Entering item %p (%s), flag %x, cause %x, state %d\n",
3908           newSelect, TREEVIEW_ItemName(newSelect), action, cause,
3909           newSelect ? newSelect->state : 0);
3910
3911     /* reset and redraw focusedItem if focusedItem was set so we don't */
3912     /* have to worry about the previously focused item when we set a new one */
3913     if(infoPtr->focusedItem)
3914     {
3915         rcFocused = (infoPtr->focusedItem)->rect;
3916         infoPtr->focusedItem = 0;
3917         InvalidateRect(infoPtr->hwnd, &rcFocused, TRUE);
3918     }
3919
3920     switch (action)
3921     {
3922     case TVGN_CARET:
3923         prevSelect = infoPtr->selectedItem;
3924
3925         if (prevSelect == newSelect)
3926             return FALSE;
3927
3928         if (TREEVIEW_SendTreeviewNotify(infoPtr,
3929                                         TVN_SELCHANGINGA,
3930                                         cause,
3931                                         TVIF_HANDLE | TVIF_STATE | TVIF_PARAM,
3932                                         prevSelect,
3933                                         newSelect))
3934             return FALSE;
3935
3936         if (prevSelect)
3937             prevSelect->state &= ~TVIS_SELECTED;
3938         if (newSelect)
3939             newSelect->state |= TVIS_SELECTED;
3940
3941         infoPtr->selectedItem = newSelect;
3942
3943         TREEVIEW_EnsureVisible(infoPtr, infoPtr->selectedItem, FALSE);
3944
3945         TREEVIEW_SendTreeviewNotify(infoPtr,
3946                                     TVN_SELCHANGEDA,
3947                                     cause,
3948                                     TVIF_HANDLE | TVIF_STATE | TVIF_PARAM,
3949                                     prevSelect,
3950                                     newSelect);
3951         TREEVIEW_QueueItemRefresh(infoPtr, prevSelect);
3952         TREEVIEW_QueueItemRefresh(infoPtr, newSelect);
3953         break;
3954
3955     case TVGN_DROPHILITE:
3956         prevSelect = infoPtr->dropItem;
3957
3958         if (prevSelect)
3959             prevSelect->state &= ~TVIS_DROPHILITED;
3960
3961         infoPtr->dropItem = newSelect;
3962
3963         if (newSelect)
3964             newSelect->state |= TVIS_DROPHILITED;
3965
3966         TREEVIEW_QueueItemRefresh(infoPtr, prevSelect);
3967         TREEVIEW_QueueItemRefresh(infoPtr, newSelect);
3968         break;
3969
3970     case TVGN_FIRSTVISIBLE:
3971         TREEVIEW_EnsureVisible(infoPtr, newSelect, FALSE);
3972         TREEVIEW_SetFirstVisible(infoPtr, newSelect, TRUE);
3973         TREEVIEW_QueueRefresh(infoPtr);
3974         break;
3975     }
3976
3977     TRACE("Leaving state %d\n", newSelect ? newSelect->state : 0);
3978     return TRUE;
3979 }
3980
3981 /* FIXME: handle NM_KILLFOCUS etc */
3982 static LRESULT
3983 TREEVIEW_SelectItem(TREEVIEW_INFO *infoPtr, INT wParam, HTREEITEM item)
3984 {
3985     if (item != NULL && !TREEVIEW_ValidItem(infoPtr, item))
3986         return FALSE;
3987
3988     TRACE("%p (%s) %d\n", item, TREEVIEW_ItemName(item), wParam);
3989
3990     if (!TREEVIEW_DoSelectItem(infoPtr, wParam, item, TVC_UNKNOWN))
3991         return FALSE;
3992
3993     return TRUE;
3994 }
3995
3996 /* Scrolling ************************************************************/
3997
3998 static LRESULT
3999 TREEVIEW_EnsureVisible(TREEVIEW_INFO *infoPtr, HTREEITEM item, BOOL bHScroll)
4000 {
4001     HTREEITEM newFirstVisible = NULL;
4002     int visible_pos;
4003
4004     if (!TREEVIEW_ValidItem(infoPtr, item))
4005         return FALSE;
4006
4007     if (!ISVISIBLE(item))
4008     {
4009         /* Expand parents as necessary. */
4010         HTREEITEM parent;
4011
4012         /* see if we are trying to ensure that root is vislble */
4013         if((item != infoPtr->root) && TREEVIEW_ValidItem(infoPtr, item))
4014           parent = item->parent;
4015         else
4016           parent = item; /* this item is the topmost item */
4017
4018         while (parent != infoPtr->root)
4019         {
4020             if (!(parent->state & TVIS_EXPANDED))
4021                 TREEVIEW_Expand(infoPtr, parent, FALSE, FALSE);
4022
4023             parent = parent->parent;
4024         }
4025     }
4026
4027     TRACE("%p (%s) %ld - %ld\n", item, TREEVIEW_ItemName(item), item->visibleOrder,
4028           infoPtr->firstVisible->visibleOrder);
4029
4030     visible_pos = item->visibleOrder - infoPtr->firstVisible->visibleOrder;
4031
4032     if (visible_pos < 0)
4033     {
4034         /* item is before the start of the list: put it at the top. */
4035         newFirstVisible = item;
4036     }
4037     else if (visible_pos >= TREEVIEW_GetVisibleCount(infoPtr)
4038              /* Sometimes, before we are displayed, GVC is 0, causing us to
4039               * spuriously scroll up. */
4040              && visible_pos > 0)
4041     {
4042         /* item is past the end of the list. */
4043         int scroll = visible_pos - TREEVIEW_GetVisibleCount(infoPtr);
4044
4045         newFirstVisible = TREEVIEW_GetListItem(infoPtr, infoPtr->firstVisible,
4046                                                scroll + 1);
4047     }
4048
4049     if (bHScroll)
4050     {
4051         /* Scroll window so item's text is visible as much as possible */
4052         /* Calculation of amount of extra space is taken from EditLabel code */
4053         INT pos, x;
4054         TEXTMETRICA textMetric;
4055         HDC hdc = GetWindowDC(infoPtr->hwnd);
4056
4057         x = item->textWidth;
4058
4059         GetTextMetricsA(hdc, &textMetric);
4060         ReleaseDC(infoPtr->hwnd, hdc);
4061
4062         x += (textMetric.tmMaxCharWidth * 2);
4063         x = max(x, textMetric.tmMaxCharWidth * 3);
4064
4065         if (item->textOffset < 0)
4066            pos = item->textOffset;
4067         else if (item->textOffset + x > infoPtr->clientWidth)
4068         {
4069            if (x > infoPtr->clientWidth)
4070               pos = item->textOffset;
4071            else
4072               pos = item->textOffset + x - infoPtr->clientWidth;
4073         }
4074         else
4075            pos = 0;
4076
4077         TREEVIEW_HScroll(infoPtr, MAKEWPARAM(SB_THUMBPOSITION, infoPtr->scrollX + pos));
4078     }
4079
4080     if (newFirstVisible != NULL && newFirstVisible != infoPtr->firstVisible)
4081     {
4082         TREEVIEW_SetFirstVisible(infoPtr, newFirstVisible, TRUE);
4083
4084         return TRUE;
4085     }
4086
4087     return FALSE;
4088 }
4089
4090 static VOID
4091 TREEVIEW_SetFirstVisible(TREEVIEW_INFO *infoPtr,
4092                          TREEVIEW_ITEM *newFirstVisible,
4093                          BOOL bUpdateScrollPos)
4094 {
4095     int gap_size;
4096
4097     TRACE("%p: %s\n", newFirstVisible, TREEVIEW_ItemName(newFirstVisible));
4098
4099     if (newFirstVisible != NULL)
4100     {
4101         /* Prevent an empty gap from appearing at the bottom... */
4102         gap_size = TREEVIEW_GetVisibleCount(infoPtr)
4103             - infoPtr->maxVisibleOrder + newFirstVisible->visibleOrder;
4104
4105         if (gap_size > 0)
4106         {
4107             newFirstVisible = TREEVIEW_GetListItem(infoPtr, newFirstVisible,
4108                                                    -gap_size);
4109
4110             /* ... unless we just don't have enough items. */
4111             if (newFirstVisible == NULL)
4112                 newFirstVisible = infoPtr->root->firstChild;
4113         }
4114     }
4115
4116     if (infoPtr->firstVisible != newFirstVisible)
4117     {
4118         if (infoPtr->firstVisible == NULL || newFirstVisible == NULL)
4119         {
4120             infoPtr->firstVisible = newFirstVisible;
4121             TREEVIEW_QueueRefresh(infoPtr);
4122         }
4123         else
4124         {
4125             TREEVIEW_ITEM *item;
4126             int scroll = infoPtr->uItemHeight *
4127                          (infoPtr->firstVisible->visibleOrder
4128                           - newFirstVisible->visibleOrder);
4129
4130             infoPtr->firstVisible = newFirstVisible;
4131
4132             for (item = infoPtr->root->firstChild; item != NULL;
4133                  item = TREEVIEW_GetNextListItem(infoPtr, item))
4134             {
4135                item->rect.top += scroll;
4136                item->rect.bottom += scroll;
4137             }
4138
4139             if (bUpdateScrollPos)
4140                 SetScrollPos(infoPtr->hwnd, SB_VERT,
4141                               newFirstVisible->visibleOrder, TRUE);
4142
4143             ScrollWindow(infoPtr->hwnd, 0, scroll, NULL, NULL);
4144             UpdateWindow(infoPtr->hwnd);
4145         }
4146     }
4147 }
4148
4149 /************************************************************************
4150  * VScroll is always in units of visible items. i.e. we always have a
4151  * visible item aligned to the top of the control. (Unless we have no
4152  * items at all.)
4153  */
4154 static LRESULT
4155 TREEVIEW_VScroll(TREEVIEW_INFO *infoPtr, WPARAM wParam)
4156 {
4157     TREEVIEW_ITEM *oldFirstVisible = infoPtr->firstVisible;
4158     TREEVIEW_ITEM *newFirstVisible = NULL;
4159
4160     int nScrollCode = LOWORD(wParam);
4161
4162     TRACE("wp %x\n", wParam);
4163
4164     if (!(infoPtr->uInternalStatus & TV_VSCROLL))
4165         return 0;
4166
4167     if (infoPtr->hwndEdit)
4168         SetFocus(infoPtr->hwnd);
4169
4170     if (!oldFirstVisible)
4171     {
4172         assert(infoPtr->root->firstChild == NULL);
4173         return 0;
4174     }
4175
4176     switch (nScrollCode)
4177     {
4178     case SB_TOP:
4179         newFirstVisible = infoPtr->root->firstChild;
4180         break;
4181
4182     case SB_BOTTOM:
4183         newFirstVisible = TREEVIEW_GetLastListItem(infoPtr, infoPtr->root);
4184         break;
4185
4186     case SB_LINEUP:
4187         newFirstVisible = TREEVIEW_GetPrevListItem(infoPtr, oldFirstVisible);
4188         break;
4189
4190     case SB_LINEDOWN:
4191         newFirstVisible = TREEVIEW_GetNextListItem(infoPtr, oldFirstVisible);
4192         break;
4193
4194     case SB_PAGEUP:
4195         newFirstVisible = TREEVIEW_GetListItem(infoPtr, oldFirstVisible,
4196                                                -max(1, TREEVIEW_GetVisibleCount(infoPtr)));
4197         break;
4198
4199     case SB_PAGEDOWN:
4200         newFirstVisible = TREEVIEW_GetListItem(infoPtr, oldFirstVisible,
4201                                                max(1, TREEVIEW_GetVisibleCount(infoPtr)));
4202         break;
4203
4204     case SB_THUMBTRACK:
4205     case SB_THUMBPOSITION:
4206         newFirstVisible = TREEVIEW_GetListItem(infoPtr,
4207                                                infoPtr->root->firstChild,
4208                                                (LONG)(INT16)HIWORD(wParam));
4209         break;
4210
4211     case SB_ENDSCROLL:
4212         return 0;
4213     }
4214
4215     if (newFirstVisible != NULL)
4216     {
4217         if (newFirstVisible != oldFirstVisible)
4218             TREEVIEW_SetFirstVisible(infoPtr, newFirstVisible,
4219                                   nScrollCode != SB_THUMBTRACK);
4220         else if (nScrollCode == SB_THUMBPOSITION)
4221             SetScrollPos(infoPtr->hwnd, SB_VERT,
4222                          newFirstVisible->visibleOrder, TRUE);
4223     }
4224
4225     return 0;
4226 }
4227
4228 static LRESULT
4229 TREEVIEW_HScroll(TREEVIEW_INFO *infoPtr, WPARAM wParam)
4230 {
4231     int maxWidth;
4232     int scrollX = infoPtr->scrollX;
4233     int nScrollCode = LOWORD(wParam);
4234
4235     TRACE("wp %x\n", wParam);
4236
4237     if (!(infoPtr->uInternalStatus & TV_HSCROLL))
4238         return FALSE;
4239
4240     if (infoPtr->hwndEdit)
4241         SetFocus(infoPtr->hwnd);
4242
4243     maxWidth = infoPtr->treeWidth - infoPtr->clientWidth;
4244     /* shall never occure */
4245     if (maxWidth <= 0)
4246     {
4247        scrollX = 0;
4248        goto scroll;
4249     }
4250
4251     switch (nScrollCode)
4252     {
4253     case SB_LINELEFT:
4254         scrollX -= infoPtr->uItemHeight;
4255         break;
4256     case SB_LINERIGHT:
4257         scrollX += infoPtr->uItemHeight;
4258         break;
4259     case SB_PAGELEFT:
4260         scrollX -= infoPtr->clientWidth;
4261         break;
4262     case SB_PAGERIGHT:
4263         scrollX += infoPtr->clientWidth;
4264         break;
4265
4266     case SB_THUMBTRACK:
4267     case SB_THUMBPOSITION:
4268         scrollX = (int)(INT16)HIWORD(wParam);
4269         break;
4270
4271     case SB_ENDSCROLL:
4272        return 0;
4273     }
4274
4275     if (scrollX > maxWidth)
4276         scrollX = maxWidth;
4277     else if (scrollX < 0)
4278         scrollX = 0;
4279
4280 scroll:
4281     if (scrollX != infoPtr->scrollX)
4282     {
4283         TREEVIEW_ITEM *item;
4284         LONG scroll_pixels = infoPtr->scrollX - scrollX;
4285         
4286         for (item = infoPtr->root->firstChild; item != NULL;
4287              item = TREEVIEW_GetNextListItem(infoPtr, item))
4288         {
4289            item->linesOffset += scroll_pixels;
4290            item->stateOffset += scroll_pixels;
4291            item->imageOffset += scroll_pixels;
4292            item->textOffset  += scroll_pixels;
4293         }
4294
4295         ScrollWindow(infoPtr->hwnd, scroll_pixels, 0, NULL, NULL);
4296         infoPtr->scrollX = scrollX;
4297         UpdateWindow(infoPtr->hwnd);
4298     }
4299
4300     if (nScrollCode != SB_THUMBTRACK)
4301        SetScrollPos(infoPtr->hwnd, SB_HORZ, scrollX, TRUE);
4302
4303     return 0;
4304 }
4305
4306 static LRESULT
4307 TREEVIEW_MouseWheel(TREEVIEW_INFO *infoPtr, WPARAM wParam)
4308 {
4309     short gcWheelDelta;
4310     UINT pulScrollLines = 3;
4311
4312     if (infoPtr->firstVisible == NULL)
4313         return TRUE;
4314
4315     SystemParametersInfoW(SPI_GETWHEELSCROLLLINES, 0, &pulScrollLines, 0);
4316
4317     gcWheelDelta = -(short)HIWORD(wParam);
4318     pulScrollLines *= (gcWheelDelta / WHEEL_DELTA);
4319
4320     if (abs(gcWheelDelta) >= WHEEL_DELTA && pulScrollLines)
4321     {
4322         int newDy = infoPtr->firstVisible->visibleOrder + pulScrollLines;
4323         int maxDy = infoPtr->maxVisibleOrder;
4324
4325         if (newDy > maxDy)
4326             newDy = maxDy;
4327
4328         if (newDy < 0)
4329             newDy = 0;
4330
4331         TREEVIEW_VScroll(infoPtr, MAKEWPARAM(SB_THUMBPOSITION, newDy));
4332     }
4333     return TRUE;
4334 }
4335
4336 /* Create/Destroy *******************************************************/
4337
4338 static LRESULT
4339 TREEVIEW_Create(HWND hwnd)
4340
4341     RECT rcClient;
4342     TREEVIEW_INFO *infoPtr;
4343
4344     TRACE("wnd %x, style %lx\n", hwnd, GetWindowLongA(hwnd, GWL_STYLE));
4345
4346     infoPtr = (TREEVIEW_INFO *)COMCTL32_Alloc(sizeof(TREEVIEW_INFO));
4347  
4348     if (infoPtr == NULL)
4349     {
4350         ERR("could not allocate info memory!\n");
4351         return 0;
4352     }
4353
4354     SetWindowLongA(hwnd, 0, (DWORD)infoPtr);
4355
4356     infoPtr->hwnd = hwnd;
4357     infoPtr->dwStyle = GetWindowLongA(hwnd, GWL_STYLE);
4358     infoPtr->uInternalStatus = 0;
4359     infoPtr->Timer = 0;
4360     infoPtr->uNumItems = 0;
4361     infoPtr->cdmode = 0;
4362     infoPtr->uScrollTime = 300; /* milliseconds */
4363     infoPtr->bRedraw = TRUE;
4364
4365     GetClientRect(hwnd, &rcClient);
4366
4367     /* No scroll bars yet. */
4368     infoPtr->clientWidth = rcClient.right;
4369     infoPtr->clientHeight = rcClient.bottom;
4370
4371     infoPtr->treeWidth = 0;
4372     infoPtr->treeHeight = 0;
4373
4374     infoPtr->uIndent = 19;
4375     infoPtr->selectedItem = 0;
4376     infoPtr->focusedItem = 0;
4377     /* hotItem? */
4378     infoPtr->firstVisible = 0;
4379     infoPtr->maxVisibleOrder = 0;
4380     infoPtr->dropItem = 0;
4381     infoPtr->insertMarkItem = 0;
4382     infoPtr->insertBeforeorAfter = 0;
4383     /* dragList */
4384
4385     infoPtr->scrollX = 0;
4386
4387     infoPtr->clrBk = GetSysColor(COLOR_WINDOW);
4388     infoPtr->clrText = -1;      /* use system color */
4389     infoPtr->clrLine = RGB(128, 128, 128);
4390     infoPtr->clrInsertMark = GetSysColor(COLOR_BTNTEXT);
4391
4392     /* hwndToolTip */
4393
4394     infoPtr->hwndEdit = 0;
4395     infoPtr->wpEditOrig = NULL;
4396     infoPtr->bIgnoreEditKillFocus = FALSE;
4397     infoPtr->bLabelChanged = FALSE;
4398
4399     infoPtr->himlNormal = NULL;
4400     infoPtr->himlState = NULL;
4401     infoPtr->normalImageWidth = 0;
4402     infoPtr->normalImageHeight = 0;
4403     infoPtr->stateImageWidth = 0;
4404     infoPtr->stateImageHeight = 0;
4405
4406     infoPtr->items = DPA_Create(16);
4407
4408     infoPtr->hFont = GetStockObject(DEFAULT_GUI_FONT);
4409     infoPtr->hBoldFont = TREEVIEW_CreateBoldFont(infoPtr->hFont);
4410
4411     infoPtr->uItemHeight = TREEVIEW_NaturalHeight(infoPtr);
4412
4413     infoPtr->root = TREEVIEW_AllocateItem(infoPtr);
4414     infoPtr->root->state = TVIS_EXPANDED;
4415     infoPtr->root->iLevel = -1;
4416     infoPtr->root->visibleOrder = -1;
4417
4418 #if 0
4419     infoPtr->hwndNotify = GetParent32 (hwnd);
4420     infoPtr->bTransparent = ( GetWindowLongA( hwnd, GWL_STYLE) & TBSTYLE_FLAT);
4421 #endif
4422
4423     infoPtr->hwndToolTip = 0;
4424     if (!(infoPtr->dwStyle & TVS_NOTOOLTIPS))
4425         infoPtr->hwndToolTip = COMCTL32_CreateToolTip(hwnd);
4426
4427     if (infoPtr->dwStyle & TVS_CHECKBOXES)
4428     {
4429         RECT rc;
4430         HBITMAP hbm, hbmOld;
4431         HDC hdc;
4432         int nIndex;
4433
4434         infoPtr->himlState =
4435             ImageList_Create(16, 16, ILC_COLOR | ILC_MASK, 3, 0);
4436
4437         hdc = CreateCompatibleDC(0);
4438         hbm = CreateCompatibleBitmap(hdc, 48, 16);
4439         hbmOld = SelectObject(hdc, hbm);
4440
4441         rc.left  = 0;   rc.top    = 0;
4442         rc.right = 48;  rc.bottom = 16;
4443         FillRect(hdc, &rc, (HBRUSH)(COLOR_WINDOW+1));
4444
4445         rc.left  = 18;   rc.top    = 2;
4446         rc.right = 30;   rc.bottom = 14;
4447         DrawFrameControl(hdc, &rc, DFC_BUTTON,
4448                           DFCS_BUTTONCHECK|DFCS_FLAT);
4449
4450         rc.left  = 34;   rc.right  = 46;
4451         DrawFrameControl(hdc, &rc, DFC_BUTTON,
4452                           DFCS_BUTTONCHECK|DFCS_FLAT|DFCS_CHECKED);
4453
4454         nIndex = ImageList_AddMasked(infoPtr->himlState, hbm,
4455                                       GetSysColor(COLOR_WINDOW));
4456         TRACE("chckbox index %d\n", nIndex);
4457         SelectObject(hdc, hbmOld);
4458         DeleteObject(hbm);
4459         DeleteDC(hdc);
4460
4461         infoPtr->stateImageWidth = 16;
4462         infoPtr->stateImageHeight = 16;
4463     }
4464     return 0;
4465 }
4466
4467
4468 static LRESULT
4469 TREEVIEW_Destroy(TREEVIEW_INFO *infoPtr)
4470 {
4471     TRACE("\n");
4472
4473     TREEVIEW_RemoveTree(infoPtr);
4474
4475     /* tool tip is automatically destroyed: we are its owner */
4476
4477     /* Restore original windproc. */
4478     if (infoPtr->hwndEdit)
4479         SetWindowLongA(infoPtr->hwndEdit, GWL_WNDPROC,
4480                        (LONG)infoPtr->wpEditOrig);
4481
4482     /* Deassociate treeview from the window before doing anything drastic. */
4483     SetWindowLongA(infoPtr->hwnd, 0, (LONG)NULL);
4484
4485     DeleteObject(infoPtr->hBoldFont);
4486     COMCTL32_Free(infoPtr);
4487
4488     return 0;
4489 }
4490
4491 /* Miscellaneous Messages ***********************************************/
4492
4493 static LRESULT
4494 TREEVIEW_ScrollKeyDown(TREEVIEW_INFO *infoPtr, WPARAM key)
4495 {
4496     static const struct
4497     {
4498         unsigned char code;
4499     }
4500     scroll[] =
4501     {
4502 #define SCROLL_ENTRY(dir, code) { ((dir) << 7) | (code) }
4503         SCROLL_ENTRY(SB_VERT, SB_PAGEUP),       /* VK_PRIOR */
4504         SCROLL_ENTRY(SB_VERT, SB_PAGEDOWN),     /* VK_NEXT */
4505         SCROLL_ENTRY(SB_VERT, SB_BOTTOM),       /* VK_END */
4506         SCROLL_ENTRY(SB_VERT, SB_TOP),          /* VK_HOME */
4507         SCROLL_ENTRY(SB_HORZ, SB_LINEUP),       /* VK_LEFT */
4508         SCROLL_ENTRY(SB_VERT, SB_LINEUP),       /* VK_UP */
4509         SCROLL_ENTRY(SB_HORZ, SB_LINEDOWN),     /* VK_RIGHT */
4510         SCROLL_ENTRY(SB_VERT, SB_LINEDOWN)      /* VK_DOWN */
4511 #undef SCROLL_ENTRY
4512     };
4513
4514     if (key >= VK_PRIOR && key <= VK_DOWN)
4515     {
4516         unsigned char code = scroll[key - VK_PRIOR].code;
4517
4518         (((code & (1 << 7)) == (SB_HORZ << 7))
4519          ? TREEVIEW_HScroll
4520          : TREEVIEW_VScroll)(infoPtr, code & 0x7F);
4521     }
4522
4523     return 0;
4524 }
4525
4526 /************************************************************************
4527  *        TREEVIEW_KeyDown
4528  *
4529  * VK_UP       Move selection to the previous non-hidden item.
4530  * VK_DOWN     Move selection to the next non-hidden item.
4531  * VK_HOME     Move selection to the first item.
4532  * VK_END      Move selection to the last item.
4533  * VK_LEFT     If expanded then collapse, otherwise move to parent.
4534  * VK_RIGHT    If collapsed then expand, otherwise move to first child.
4535  * VK_ADD      Expand.
4536  * VK_SUBTRACT Collapse.
4537  * VK_MULTIPLY Expand all.
4538  * VK_PRIOR    Move up GetVisibleCount items.
4539  * VK_NEXT     Move down GetVisibleCount items.
4540  * VK_BACK     Move to parent.
4541  * CTRL-Left,Right,Up,Down,PgUp,PgDown,Home,End: Scroll without changing selection
4542  */
4543 static LRESULT
4544 TREEVIEW_KeyDown(TREEVIEW_INFO *infoPtr, WPARAM wParam)
4545 {
4546     /* If it is non-NULL and different, it will be selected and visible. */
4547     TREEVIEW_ITEM *newSelection = NULL;
4548
4549     TREEVIEW_ITEM *prevItem = infoPtr->selectedItem;
4550
4551     TRACE("%x\n", wParam);
4552
4553     if (prevItem == NULL)
4554         return FALSE;
4555
4556     if (GetAsyncKeyState(VK_CONTROL) & 0x8000)
4557         return TREEVIEW_ScrollKeyDown(infoPtr, wParam);
4558
4559     switch (wParam)
4560     {
4561     case VK_UP:
4562         newSelection = TREEVIEW_GetPrevListItem(infoPtr, prevItem);
4563         if (!newSelection)
4564             newSelection = infoPtr->root->firstChild;
4565         break;
4566
4567     case VK_DOWN:
4568         newSelection = TREEVIEW_GetNextListItem(infoPtr, prevItem);
4569         break;
4570
4571     case VK_HOME:
4572         newSelection = infoPtr->root->firstChild;
4573         break;
4574
4575     case VK_END:
4576         newSelection = TREEVIEW_GetLastListItem(infoPtr, infoPtr->root);
4577         break;
4578
4579     case VK_LEFT:
4580         if (prevItem->state & TVIS_EXPANDED)
4581         {
4582             TREEVIEW_Collapse(infoPtr, prevItem, FALSE, TRUE);
4583         }
4584         else if (prevItem->parent != infoPtr->root)
4585         {
4586             newSelection = prevItem->parent;
4587         }
4588         break;
4589
4590     case VK_RIGHT:
4591         if (TREEVIEW_HasChildren(infoPtr, prevItem))
4592         {
4593             if (!(prevItem->state & TVIS_EXPANDED))
4594                 TREEVIEW_Expand(infoPtr, prevItem, FALSE, TRUE);
4595             else
4596             {
4597                 newSelection = prevItem->firstChild;
4598             }
4599         }
4600
4601         break;
4602
4603     case VK_MULTIPLY:
4604         TREEVIEW_ExpandAll(infoPtr, prevItem);
4605         break;
4606
4607     case VK_ADD:
4608         if (!(prevItem->state & TVIS_EXPANDED))
4609             TREEVIEW_Expand(infoPtr, prevItem, FALSE, TRUE);
4610         break;
4611
4612     case VK_SUBTRACT:
4613         if (prevItem->state & TVIS_EXPANDED)
4614             TREEVIEW_Collapse(infoPtr, prevItem, FALSE, TRUE);
4615         break;
4616
4617     case VK_PRIOR:
4618         newSelection
4619             = TREEVIEW_GetListItem(infoPtr, prevItem,
4620                                    -TREEVIEW_GetVisibleCount(infoPtr));
4621         break;
4622
4623     case VK_NEXT:
4624         newSelection
4625             = TREEVIEW_GetListItem(infoPtr, prevItem,
4626                                    TREEVIEW_GetVisibleCount(infoPtr));
4627         break;
4628
4629     case VK_BACK:
4630         newSelection = prevItem->parent;
4631         if (newSelection == infoPtr->root)
4632             newSelection = NULL;
4633         break;
4634
4635     case VK_SPACE:
4636         if (infoPtr->dwStyle & TVS_CHECKBOXES)
4637             TREEVIEW_ToggleItemState(infoPtr, prevItem);
4638         break;
4639     }
4640
4641     if (newSelection && newSelection != prevItem)
4642     {
4643         if (TREEVIEW_DoSelectItem(infoPtr, TVGN_CARET, newSelection,
4644                                   TVC_BYKEYBOARD))
4645         {
4646             TREEVIEW_EnsureVisible(infoPtr, newSelection, FALSE);
4647         }
4648     }
4649
4650     return FALSE;
4651 }
4652
4653 static LRESULT
4654 TREEVIEW_Size(TREEVIEW_INFO *infoPtr, WPARAM wParam, LPARAM lParam)
4655 {
4656     if (wParam == SIZE_RESTORED)
4657     {
4658         infoPtr->clientWidth  = (LONG)(INT16)LOWORD(lParam);
4659         infoPtr->clientHeight = (LONG)(INT16)HIWORD(lParam);
4660
4661         TREEVIEW_RecalculateVisibleOrder(infoPtr, NULL);
4662         TREEVIEW_SetFirstVisible(infoPtr, infoPtr->firstVisible, TRUE);
4663         TREEVIEW_UpdateScrollBars(infoPtr);
4664     }
4665     else
4666     {
4667         FIXME("WM_SIZE flag %x %lx not handled\n", wParam, lParam);
4668     }
4669
4670     TREEVIEW_QueueRefresh(infoPtr);
4671     return 0;
4672 }
4673
4674 static LRESULT
4675 TREEVIEW_StyleChanged(TREEVIEW_INFO *infoPtr, WPARAM wParam, LPARAM lParam)
4676 {
4677     TRACE("(%x %lx)\n", wParam, lParam);
4678
4679     if (wParam == GWL_STYLE)
4680     {
4681        DWORD dwNewStyle = ((LPSTYLESTRUCT)lParam)->styleNew;
4682
4683        /* we have to take special care about tooltips */
4684        if ((infoPtr->dwStyle ^ dwNewStyle) & TVS_NOTOOLTIPS)
4685        {
4686           if (infoPtr->dwStyle & TVS_NOTOOLTIPS)
4687           {
4688               infoPtr->hwndToolTip = COMCTL32_CreateToolTip(infoPtr->hwnd);
4689               TRACE("\n");
4690           }
4691           else
4692           {
4693              DestroyWindow(infoPtr->hwndToolTip);
4694              infoPtr->hwndToolTip = 0;
4695           }
4696        }
4697
4698        infoPtr->dwStyle = dwNewStyle;
4699     }
4700
4701     TREEVIEW_UpdateSubTree(infoPtr, infoPtr->root);
4702     TREEVIEW_UpdateScrollBars(infoPtr);
4703     TREEVIEW_QueueRefresh(infoPtr);
4704
4705     return 0;
4706 }
4707
4708 static LRESULT
4709 TREEVIEW_SetFocus(TREEVIEW_INFO *infoPtr)
4710 {
4711     TRACE("\n");
4712
4713     if (!infoPtr->selectedItem)
4714     {
4715         TREEVIEW_DoSelectItem(infoPtr, TVGN_CARET, infoPtr->firstVisible,
4716                               TVC_UNKNOWN);
4717     }
4718
4719     TREEVIEW_SendSimpleNotify(infoPtr, NM_SETFOCUS);
4720     TREEVIEW_QueueItemRefresh(infoPtr, infoPtr->selectedItem);
4721     return 0;
4722 }
4723
4724 static LRESULT
4725 TREEVIEW_KillFocus(TREEVIEW_INFO *infoPtr)
4726 {
4727     TRACE("\n");
4728
4729     TREEVIEW_SendSimpleNotify(infoPtr, NM_KILLFOCUS);
4730     TREEVIEW_QueueItemRefresh(infoPtr, infoPtr->selectedItem);
4731     return 0;
4732 }
4733
4734
4735 static LRESULT WINAPI
4736 TREEVIEW_WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
4737 {
4738     TREEVIEW_INFO *infoPtr = TREEVIEW_GetInfoPtr(hwnd);
4739     if (infoPtr) TREEVIEW_VerifyTree(infoPtr);
4740     else
4741     {
4742         if (uMsg == WM_CREATE)
4743             TREEVIEW_Create(hwnd);
4744         else
4745             goto def;
4746     }
4747
4748     switch (uMsg)
4749     {
4750     case TVM_CREATEDRAGIMAGE:
4751         return TREEVIEW_CreateDragImage(infoPtr, wParam, lParam);
4752
4753     case TVM_DELETEITEM:
4754         return TREEVIEW_DeleteItem(infoPtr, (HTREEITEM)lParam);
4755
4756     case TVM_EDITLABELA:
4757         return TREEVIEW_EditLabelA(infoPtr, (HTREEITEM)lParam);
4758
4759     case TVM_EDITLABELW:
4760         FIXME("Unimplemented msg TVM_EDITLABELW\n");
4761         return 0;
4762
4763     case TVM_ENDEDITLABELNOW:
4764         return TREEVIEW_EndEditLabelNow(infoPtr, (BOOL)wParam);
4765
4766     case TVM_ENSUREVISIBLE:
4767         return TREEVIEW_EnsureVisible(infoPtr, (HTREEITEM)lParam, TRUE);
4768
4769     case TVM_EXPAND:
4770         return TREEVIEW_ExpandMsg(infoPtr, (UINT)wParam, (HTREEITEM)lParam);
4771
4772     case TVM_GETBKCOLOR:
4773         return TREEVIEW_GetBkColor(infoPtr);
4774
4775     case TVM_GETCOUNT:
4776         return TREEVIEW_GetCount(infoPtr);
4777
4778     case TVM_GETEDITCONTROL:
4779         return TREEVIEW_GetEditControl(infoPtr);
4780
4781     case TVM_GETIMAGELIST:
4782         return TREEVIEW_GetImageList(infoPtr, wParam);
4783
4784     case TVM_GETINDENT:
4785         return TREEVIEW_GetIndent(infoPtr);
4786
4787     case TVM_GETINSERTMARKCOLOR:
4788         return TREEVIEW_GetInsertMarkColor(infoPtr);
4789
4790     case TVM_GETISEARCHSTRINGA:
4791         FIXME("Unimplemented msg TVM_GETISEARCHSTRINGA\n");
4792         return 0;
4793
4794     case TVM_GETISEARCHSTRINGW:
4795         FIXME("Unimplemented msg TVM_GETISEARCHSTRINGW\n");
4796         return 0;
4797
4798     case TVM_GETITEMA:
4799         return TREEVIEW_GetItemA(infoPtr, (LPTVITEMEXA)lParam);
4800
4801     case TVM_GETITEMW:
4802         return TREEVIEW_GetItemW(infoPtr, (LPTVITEMEXA)lParam);
4803
4804     case TVM_GETITEMHEIGHT:
4805         return TREEVIEW_GetItemHeight(infoPtr);
4806
4807     case TVM_GETITEMRECT:
4808         return TREEVIEW_GetItemRect(infoPtr, (BOOL)wParam, (LPRECT)lParam);
4809
4810     case TVM_GETITEMSTATE:
4811         return TREEVIEW_GetItemState(infoPtr, (HTREEITEM)wParam, (UINT)lParam);
4812
4813     case TVM_GETLINECOLOR:
4814         return TREEVIEW_GetLineColor(infoPtr);
4815
4816     case TVM_GETNEXTITEM:
4817         return TREEVIEW_GetNextItem(infoPtr, (UINT)wParam, (HTREEITEM)lParam);
4818
4819     case TVM_GETSCROLLTIME:
4820         return TREEVIEW_GetScrollTime(infoPtr);
4821
4822     case TVM_GETTEXTCOLOR:
4823         return TREEVIEW_GetTextColor(infoPtr);
4824
4825     case TVM_GETTOOLTIPS:
4826         return TREEVIEW_GetToolTips(infoPtr);
4827
4828     case TVM_GETUNICODEFORMAT:
4829         FIXME("Unimplemented msg TVM_GETUNICODEFORMAT\n");
4830         return 0;
4831
4832     case TVM_GETVISIBLECOUNT:
4833         return TREEVIEW_GetVisibleCount(infoPtr);
4834
4835     case TVM_HITTEST:
4836         return TREEVIEW_HitTest(infoPtr, (LPTVHITTESTINFO)lParam);
4837
4838     case TVM_INSERTITEMA:
4839         return TREEVIEW_InsertItemA(infoPtr, lParam);
4840
4841     case TVM_INSERTITEMW:
4842         return TREEVIEW_InsertItemW(infoPtr, lParam);
4843
4844     case TVM_SELECTITEM:
4845         return TREEVIEW_SelectItem(infoPtr, (INT)wParam, (HTREEITEM)lParam);
4846
4847     case TVM_SETBKCOLOR:
4848         return TREEVIEW_SetBkColor(infoPtr, (COLORREF)lParam);
4849
4850     case TVM_SETIMAGELIST:
4851         return TREEVIEW_SetImageList(infoPtr, wParam, (HIMAGELIST)lParam);
4852
4853     case TVM_SETINDENT:
4854         return TREEVIEW_SetIndent(infoPtr, (UINT)wParam);
4855
4856     case TVM_SETINSERTMARK:
4857         return TREEVIEW_SetInsertMark(infoPtr, (BOOL)wParam, (HTREEITEM)lParam);
4858
4859     case TVM_SETINSERTMARKCOLOR:
4860         return TREEVIEW_SetInsertMarkColor(infoPtr, (COLORREF)lParam);
4861
4862     case TVM_SETITEMA:
4863         return TREEVIEW_SetItemA(infoPtr, (LPTVITEMEXA)lParam);
4864
4865     case TVM_SETITEMW:
4866         FIXME("Unimplemented msg TVM_SETITEMW\n");
4867         return 0;
4868
4869     case TVM_SETLINECOLOR:
4870         return TREEVIEW_SetLineColor(infoPtr, (COLORREF)lParam);
4871
4872     case TVM_SETITEMHEIGHT:
4873         return TREEVIEW_SetItemHeight(infoPtr, (INT)(SHORT)wParam);
4874
4875     case TVM_SETSCROLLTIME:
4876         return TREEVIEW_SetScrollTime(infoPtr, (UINT)wParam);
4877
4878     case TVM_SETTEXTCOLOR:
4879         return TREEVIEW_SetTextColor(infoPtr, (COLORREF)lParam);
4880
4881     case TVM_SETTOOLTIPS:
4882         return TREEVIEW_SetToolTips(infoPtr, (HWND)wParam);
4883
4884     case TVM_SETUNICODEFORMAT:
4885         FIXME("Unimplemented msg TVM_SETUNICODEFORMAT\n");
4886         return 0;
4887
4888     case TVM_SORTCHILDREN:
4889         return TREEVIEW_SortChildren(infoPtr, wParam, lParam);
4890
4891     case TVM_SORTCHILDRENCB:
4892         return TREEVIEW_SortChildrenCB(infoPtr, wParam, (LPTVSORTCB)lParam);
4893
4894         /* WM_CHAR */
4895
4896     case WM_COMMAND:
4897         return TREEVIEW_Command(infoPtr, wParam, lParam);
4898
4899     case WM_DESTROY:
4900         return TREEVIEW_Destroy(infoPtr);
4901
4902         /* WM_ENABLE */
4903
4904     case WM_ERASEBKGND:
4905         return TREEVIEW_EraseBackground(infoPtr, (HDC)wParam);
4906
4907     case WM_GETDLGCODE:
4908         return DLGC_WANTARROWS | DLGC_WANTCHARS;
4909
4910     case WM_GETFONT:
4911         return TREEVIEW_GetFont(infoPtr);
4912
4913     case WM_HSCROLL:
4914         return TREEVIEW_HScroll(infoPtr, wParam);
4915
4916     case WM_KEYDOWN:
4917         return TREEVIEW_KeyDown(infoPtr, wParam);
4918
4919     case WM_KILLFOCUS:
4920         return TREEVIEW_KillFocus(infoPtr);
4921
4922     case WM_LBUTTONDBLCLK:
4923         return TREEVIEW_LButtonDoubleClick(infoPtr, lParam);
4924
4925     case WM_LBUTTONDOWN:
4926         return TREEVIEW_LButtonDown(infoPtr, lParam);
4927
4928         /* WM_MBUTTONDOWN */
4929
4930         /* WM_MOUSEMOVE */
4931
4932         /* WM_NOTIFY */
4933
4934         /* WM_NOTIFYFORMAT */
4935
4936     case WM_PAINT:
4937         return TREEVIEW_Paint(infoPtr, wParam);
4938
4939         /* WM_PRINTCLIENT */
4940
4941     case WM_RBUTTONDOWN:
4942         return TREEVIEW_RButtonDown(infoPtr, lParam);
4943
4944     case WM_SETFOCUS:
4945         return TREEVIEW_SetFocus(infoPtr);
4946
4947     case WM_SETFONT:
4948         return TREEVIEW_SetFont(infoPtr, (HFONT)wParam, (BOOL)lParam);
4949
4950     case WM_SETREDRAW:
4951         return TREEVIEW_SetRedraw(infoPtr, wParam, lParam);
4952
4953     case WM_SIZE:
4954         return TREEVIEW_Size(infoPtr, wParam, lParam);
4955
4956     case WM_STYLECHANGED:
4957         return TREEVIEW_StyleChanged(infoPtr, wParam, lParam);
4958
4959         /* WM_SYSCOLORCHANGE */
4960
4961         /* WM_SYSKEYDOWN */
4962
4963     case WM_TIMER:
4964         return TREEVIEW_HandleTimer(infoPtr, wParam);
4965
4966     case WM_VSCROLL:
4967         return TREEVIEW_VScroll(infoPtr, wParam);
4968
4969         /* WM_WININICHANGE */
4970
4971     case WM_MOUSEWHEEL:
4972         if (wParam & (MK_SHIFT | MK_CONTROL))
4973             goto def;
4974         return TREEVIEW_MouseWheel(infoPtr, wParam);
4975
4976     case WM_DRAWITEM:
4977         TRACE("drawItem\n");
4978         goto def;
4979
4980     default:
4981         /* This mostly catches MFC and Delphi messages. :( */
4982         if (uMsg >= WM_USER)
4983             TRACE("Unknown msg %04x wp=%08x lp=%08lx\n", uMsg, wParam, lParam);
4984 def:
4985         return DefWindowProcA(hwnd, uMsg, wParam, lParam);
4986     }
4987     return 0;
4988 }
4989
4990
4991 /* Class Registration ***************************************************/
4992
4993 VOID
4994 TREEVIEW_Register(void)
4995 {
4996     WNDCLASSA wndClass;
4997
4998     TRACE("\n");
4999
5000     ZeroMemory(&wndClass, sizeof(WNDCLASSA));
5001     wndClass.style = CS_GLOBALCLASS | CS_DBLCLKS;
5002     wndClass.lpfnWndProc = (WNDPROC)TREEVIEW_WindowProc;
5003     wndClass.cbClsExtra = 0;
5004     wndClass.cbWndExtra = sizeof(TREEVIEW_INFO *);
5005
5006     wndClass.hCursor = LoadCursorA(0, IDC_ARROWA);
5007     wndClass.hbrBackground = 0;
5008     wndClass.lpszClassName = WC_TREEVIEWA;
5009
5010     RegisterClassA(&wndClass);
5011 }
5012
5013
5014 VOID
5015 TREEVIEW_Unregister(void)
5016 {
5017     UnregisterClassA(WC_TREEVIEWA, (HINSTANCE) NULL);
5018 }
5019
5020
5021 /* Tree Verification ****************************************************/
5022
5023 #ifndef NDEBUG
5024 static inline void
5025 TREEVIEW_VerifyChildren(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *item);
5026
5027 static inline void TREEVIEW_VerifyItemCommon(TREEVIEW_INFO *infoPtr,
5028                                              TREEVIEW_ITEM *item)
5029 {
5030     assert(infoPtr != NULL);
5031     assert(item != NULL);
5032
5033     /* both NULL, or both non-null */
5034     assert((item->firstChild == NULL) == (item->lastChild == NULL));
5035
5036     assert(item->firstChild != item);
5037     assert(item->lastChild != item);
5038
5039     if (item->firstChild)
5040     {
5041         assert(item->firstChild->parent == item);
5042         assert(item->firstChild->prevSibling == NULL);
5043     }
5044
5045     if (item->lastChild)
5046     {
5047         assert(item->lastChild->parent == item);
5048         assert(item->lastChild->nextSibling == NULL);
5049     }
5050
5051     assert(item->nextSibling != item);
5052     if (item->nextSibling)
5053     {
5054         assert(item->nextSibling->parent == item->parent);
5055         assert(item->nextSibling->prevSibling == item);
5056     }
5057
5058     assert(item->prevSibling != item);
5059     if (item->prevSibling)
5060     {
5061         assert(item->prevSibling->parent == item->parent);
5062         assert(item->prevSibling->nextSibling == item);
5063     }
5064 }
5065
5066 static inline void
5067 TREEVIEW_VerifyItem(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *item)
5068 {
5069     assert(item != NULL);
5070
5071     assert(item->parent != NULL);
5072     assert(item->parent != item);
5073     assert(item->iLevel == item->parent->iLevel + 1);
5074
5075     assert(DPA_GetPtrIndex(infoPtr->items, item) != -1);
5076
5077     TREEVIEW_VerifyItemCommon(infoPtr, item);
5078
5079     TREEVIEW_VerifyChildren(infoPtr, item);
5080 }
5081
5082 static inline void
5083 TREEVIEW_VerifyChildren(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *item)
5084 {
5085     TREEVIEW_ITEM *child;
5086     assert(item != NULL);
5087
5088     for (child = item->firstChild; child != NULL; child = child->nextSibling)
5089         TREEVIEW_VerifyItem(infoPtr, child);
5090 }
5091
5092 static inline void
5093 TREEVIEW_VerifyRoot(TREEVIEW_INFO *infoPtr)
5094 {
5095     TREEVIEW_ITEM *root = infoPtr->root;
5096
5097     assert(root != NULL);
5098     assert(root->iLevel == -1);
5099     assert(root->parent == NULL);
5100     assert(root->prevSibling == NULL);
5101
5102     TREEVIEW_VerifyItemCommon(infoPtr, root);
5103
5104     TREEVIEW_VerifyChildren(infoPtr, root);
5105 }
5106
5107 static void
5108 TREEVIEW_VerifyTree(TREEVIEW_INFO *infoPtr)
5109 {
5110     assert(infoPtr != NULL);
5111
5112     TREEVIEW_VerifyRoot(infoPtr);
5113 }
5114 #endif