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