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