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