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