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