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