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