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