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