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