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