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