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