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