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