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