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