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