Include stdio.h for MinGW.
[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             Rectangle(hdc, centerx - rectsize - 1, centery - rectsize - 1,
2323                       centerx + rectsize + 2, centery + rectsize + 2);
2324
2325             SelectObject(hdc, hbrOld);
2326             DeleteObject(hbr);
2327
2328             SelectObject(hdc, hOldPen);
2329             DeleteObject(hNewPen);
2330
2331             if (height < 16 || width < 16)
2332             {
2333                 MoveToEx(hdc, centerx - plussize + 1, centery, NULL);
2334                 LineTo(hdc, centerx + plussize, centery);
2335
2336                 if (!(item->state & TVIS_EXPANDED))
2337                 {
2338                     MoveToEx(hdc, centerx, centery - plussize + 1, NULL);
2339                     LineTo(hdc, centerx, centery + plussize);
2340                 }
2341             }
2342             else
2343             {
2344                 Rectangle(hdc, centerx - plussize + 1, centery - 1,
2345                 centerx + plussize, centery + 2);
2346
2347                 if (!(item->state & TVIS_EXPANDED))
2348                 {
2349                     Rectangle(hdc, centerx - 1, centery - plussize + 1,
2350                     centerx + 2, centery + plussize);
2351                     SetPixel(hdc, centerx - 1, centery, infoPtr->clrBk);
2352                     SetPixel(hdc, centerx + 1, centery, infoPtr->clrBk);
2353                 }
2354             }
2355         }
2356     }
2357 }
2358
2359 static void
2360 TREEVIEW_DrawItem(TREEVIEW_INFO *infoPtr, HDC hdc, TREEVIEW_ITEM *wineItem)
2361 {
2362     INT cditem;
2363     HFONT hOldFont;
2364     int centery;
2365
2366     hOldFont = SelectObject(hdc, TREEVIEW_FontForItem(infoPtr, wineItem));
2367
2368     TREEVIEW_UpdateDispInfo(infoPtr, wineItem, CALLBACK_MASK_ALL);
2369
2370     /* The custom draw handler can query the text rectangle,
2371      * so get ready. */
2372     TREEVIEW_ComputeTextWidth(infoPtr, wineItem, hdc);
2373
2374     cditem = 0;
2375
2376     if (infoPtr->cdmode & CDRF_NOTIFYITEMDRAW)
2377     {
2378         cditem = TREEVIEW_SendCustomDrawItemNotify
2379             (infoPtr, hdc, wineItem, CDDS_ITEMPREPAINT);
2380         TRACE("prepaint:cditem-app returns 0x%x\n", cditem);
2381
2382         if (cditem & CDRF_SKIPDEFAULT)
2383         {
2384             SelectObject(hdc, hOldFont);
2385             return;
2386         }
2387     }
2388
2389     if (cditem & CDRF_NEWFONT)
2390         TREEVIEW_ComputeTextWidth(infoPtr, wineItem, hdc);
2391
2392     TREEVIEW_DrawItemLines(infoPtr, hdc, wineItem);
2393
2394     centery = (wineItem->rect.top + wineItem->rect.bottom) / 2;
2395
2396     /*
2397      * Display the images associated with this item
2398      */
2399     {
2400         INT imageIndex;
2401
2402         /* State images are displayed to the left of the Normal image
2403          * image number is in state; zero should be `display no image'.
2404          */
2405         imageIndex = STATEIMAGEINDEX(wineItem->state);
2406
2407         if (infoPtr->himlState && imageIndex)
2408         {
2409             ImageList_Draw(infoPtr->himlState, imageIndex, hdc,
2410                            wineItem->stateOffset,
2411                            centery - infoPtr->stateImageHeight / 2,
2412                            ILD_NORMAL);
2413         }
2414
2415         /* Now, draw the normal image; can be either selected or
2416          * non-selected image.
2417          */
2418
2419         if ((wineItem->state & TVIS_SELECTED) && (wineItem->iSelectedImage))
2420         {
2421             /* The item is currently selected */
2422             imageIndex = wineItem->iSelectedImage;
2423         }
2424         else
2425         {
2426             /* The item is not selected */
2427             imageIndex = wineItem->iImage;
2428         }
2429
2430         if (infoPtr->himlNormal)
2431         {
2432             int ovlIdx = wineItem->state & TVIS_OVERLAYMASK;
2433
2434             ImageList_Draw(infoPtr->himlNormal, imageIndex, hdc,
2435                            wineItem->imageOffset,
2436                            centery - infoPtr->normalImageHeight / 2,
2437                            ILD_NORMAL | ovlIdx);
2438         }
2439     }
2440
2441
2442     /*
2443      * Display the text associated with this item
2444      */
2445
2446     /* Don't paint item's text if it's being edited */
2447     if (!infoPtr->hwndEdit || (infoPtr->selectedItem != wineItem))
2448     {
2449         if (wineItem->pszText)
2450         {
2451             COLORREF oldTextColor = 0;
2452             INT oldBkMode;
2453             HBRUSH hbrBk = 0;
2454             BOOL inFocus = (GetFocus() == infoPtr->hwnd);
2455             RECT rcText;
2456
2457             oldBkMode = SetBkMode(hdc, TRANSPARENT);
2458
2459             /* - If item is drop target or it is selected and window is in focus -
2460              * use blue background (COLOR_HIGHLIGHT).
2461              * - If item is selected, window is not in focus, but it has style
2462              * TVS_SHOWSELALWAYS - use grey background (COLOR_BTNFACE)
2463              * - Otherwise - don't fill background
2464              */
2465             if ((wineItem->state & TVIS_DROPHILITED) || ((wineItem == infoPtr->focusedItem) && !(wineItem->state & TVIS_SELECTED)) ||
2466                 ((wineItem->state & TVIS_SELECTED) && (!infoPtr->focusedItem) &&
2467                  (inFocus || (infoPtr->dwStyle & TVS_SHOWSELALWAYS))))
2468             {
2469                 if ((wineItem->state & TVIS_DROPHILITED) || inFocus)
2470                 {
2471                     hbrBk = CreateSolidBrush(GetSysColor(COLOR_HIGHLIGHT));
2472                     oldTextColor =
2473                         SetTextColor(hdc, GetSysColor(COLOR_HIGHLIGHTTEXT));
2474                 }
2475                 else
2476                 {
2477                     hbrBk = CreateSolidBrush(GetSysColor(COLOR_BTNFACE));
2478
2479                     if (infoPtr->clrText == -1)
2480                         oldTextColor =
2481                             SetTextColor(hdc, GetSysColor(COLOR_WINDOWTEXT));
2482                     else
2483                         oldTextColor = SetTextColor(hdc, infoPtr->clrText);
2484                 }
2485             }
2486             else
2487             {
2488                 if (infoPtr->clrText == -1)
2489                     oldTextColor =
2490                         SetTextColor(hdc, GetSysColor(COLOR_WINDOWTEXT));
2491                 else
2492                     oldTextColor = SetTextColor(hdc, infoPtr->clrText);
2493             }
2494
2495             rcText.top = wineItem->rect.top;
2496             rcText.bottom = wineItem->rect.bottom;
2497             rcText.left = wineItem->textOffset;
2498             rcText.right = rcText.left + wineItem->textWidth + 4;
2499
2500             if (hbrBk)
2501             {
2502                 FillRect(hdc, &rcText, hbrBk);
2503                 DeleteObject(hbrBk);
2504             }
2505
2506             /* Draw the box around the selected item */
2507             if ((wineItem == infoPtr->selectedItem) && inFocus)
2508             {
2509                 DrawFocusRect(hdc,&rcText);
2510             }
2511
2512             InflateRect(&rcText, -2, -1); /* allow for the focus rect */
2513
2514             TRACE("drawing text %s at (%ld,%ld)-(%ld,%ld)\n",
2515                   debugstr_w(wineItem->pszText),
2516                   rcText.left, rcText.top, rcText.right, rcText.bottom);
2517
2518             /* Draw it */
2519             DrawTextW(hdc,
2520                       wineItem->pszText,
2521                       lstrlenW(wineItem->pszText),
2522                       &rcText,
2523                       DT_CENTER | DT_VCENTER | DT_SINGLELINE | DT_NOPREFIX);
2524
2525             /* Restore the hdc state */
2526             SetTextColor(hdc, oldTextColor);
2527
2528             if (oldBkMode != TRANSPARENT)
2529                 SetBkMode(hdc, oldBkMode);
2530         }
2531     }
2532
2533     /* Draw insertion mark if necessary */
2534
2535     if (infoPtr->insertMarkItem)
2536         TRACE("item:%d,mark:%d\n",
2537               TREEVIEW_GetItemIndex(infoPtr, wineItem),
2538               (int)infoPtr->insertMarkItem);
2539
2540     if (wineItem == infoPtr->insertMarkItem)
2541     {
2542         HPEN hNewPen, hOldPen;
2543         int offset;
2544         int left, right;
2545
2546         hNewPen = CreatePen(PS_SOLID, 2, infoPtr->clrInsertMark);
2547         hOldPen = SelectObject(hdc, hNewPen);
2548
2549         if (infoPtr->insertBeforeorAfter)
2550             offset = wineItem->rect.bottom - 1;
2551         else
2552             offset = wineItem->rect.top + 1;
2553
2554         left = wineItem->textOffset - 2;
2555         right = wineItem->textOffset + wineItem->textWidth + 2;
2556
2557         MoveToEx(hdc, left, offset - 3, NULL);
2558         LineTo(hdc, left, offset + 4);
2559
2560         MoveToEx(hdc, left, offset, NULL);
2561         LineTo(hdc, right + 1, offset);
2562
2563         MoveToEx(hdc, right, offset + 3, NULL);
2564         LineTo(hdc, right, offset - 4);
2565
2566         SelectObject(hdc, hOldPen);
2567         DeleteObject(hNewPen);
2568     }
2569
2570     if (cditem & CDRF_NOTIFYPOSTPAINT)
2571     {
2572         cditem = TREEVIEW_SendCustomDrawItemNotify
2573             (infoPtr, hdc, wineItem, CDDS_ITEMPOSTPAINT);
2574         TRACE("postpaint:cditem-app returns 0x%x\n", cditem);
2575     }
2576
2577     SelectObject(hdc, hOldFont);
2578 }
2579
2580 /* Computes treeHeight and treeWidth and updates the scroll bars.
2581  */
2582 static void
2583 TREEVIEW_UpdateScrollBars(TREEVIEW_INFO *infoPtr)
2584 {
2585     TREEVIEW_ITEM *wineItem;
2586     HWND hwnd = infoPtr->hwnd;
2587     BOOL vert = FALSE;
2588     BOOL horz = FALSE;
2589     SCROLLINFO si;
2590     LONG scrollX = infoPtr->scrollX;
2591
2592     infoPtr->treeWidth = 0;
2593     infoPtr->treeHeight = 0;
2594
2595     /* We iterate through all visible items in order to get the tree height
2596      * and width */
2597     wineItem = infoPtr->root->firstChild;
2598
2599     while (wineItem != NULL)
2600     {
2601         if (ISVISIBLE(wineItem))
2602         {
2603             /* actually we draw text at textOffset + 2 */
2604             if (2+wineItem->textOffset+wineItem->textWidth > infoPtr->treeWidth)
2605                 infoPtr->treeWidth = wineItem->textOffset+wineItem->textWidth+2;
2606
2607             /* This is scroll-adjusted, but we fix this below. */
2608             infoPtr->treeHeight = wineItem->rect.bottom;
2609         }
2610
2611         wineItem = TREEVIEW_GetNextListItem(infoPtr, wineItem);
2612     }
2613
2614     /* Fix the scroll adjusted treeHeight and treeWidth. */
2615     if (infoPtr->root->firstChild)
2616         infoPtr->treeHeight -= infoPtr->root->firstChild->rect.top;
2617
2618     infoPtr->treeWidth += infoPtr->scrollX;
2619
2620     if (infoPtr->dwStyle & TVS_NOSCROLL) return;
2621
2622     /* Adding one scroll bar may take up enough space that it forces us
2623      * to add the other as well. */
2624     if (infoPtr->treeHeight > infoPtr->clientHeight)
2625     {
2626         vert = TRUE;
2627
2628         if (infoPtr->treeWidth
2629             > infoPtr->clientWidth - GetSystemMetrics(SM_CXVSCROLL))
2630             horz = TRUE;
2631     }
2632     else if (infoPtr->treeWidth > infoPtr->clientWidth)
2633         horz = TRUE;
2634
2635     if (!vert && horz && infoPtr->treeHeight
2636         > infoPtr->clientHeight - GetSystemMetrics(SM_CYVSCROLL))
2637         vert = TRUE;
2638
2639     if (horz && (infoPtr->dwStyle & TVS_NOHSCROLL)) horz = FALSE;
2640
2641     si.cbSize = sizeof(SCROLLINFO);
2642     si.fMask  = SIF_POS|SIF_RANGE|SIF_PAGE;
2643     si.nMin   = 0;
2644
2645     if (vert)
2646     {
2647         si.nPage = TREEVIEW_GetVisibleCount(infoPtr);
2648        if ( si.nPage && NULL != infoPtr->firstVisible)
2649        {
2650            si.nPos  = infoPtr->firstVisible->visibleOrder;
2651            si.nMax  = infoPtr->maxVisibleOrder - 1;
2652
2653            SetScrollInfo(hwnd, SB_VERT, &si, TRUE);
2654
2655            if (!(infoPtr->uInternalStatus & TV_VSCROLL))
2656                ShowScrollBar(hwnd, SB_VERT, TRUE);
2657            infoPtr->uInternalStatus |= TV_VSCROLL;
2658        }
2659        else
2660        {
2661            if (infoPtr->uInternalStatus & TV_VSCROLL)
2662                ShowScrollBar(hwnd, SB_VERT, FALSE);
2663            infoPtr->uInternalStatus &= ~TV_VSCROLL;
2664        }
2665     }
2666     else
2667     {
2668         if (infoPtr->uInternalStatus & TV_VSCROLL)
2669             ShowScrollBar(hwnd, SB_VERT, FALSE);
2670         infoPtr->uInternalStatus &= ~TV_VSCROLL;
2671     }
2672
2673     if (horz)
2674     {
2675         si.nPage = infoPtr->clientWidth;
2676         si.nPos  = infoPtr->scrollX;
2677         si.nMax  = infoPtr->treeWidth - 1;
2678
2679         if (si.nPos > si.nMax - max( si.nPage-1, 0 ))
2680         {
2681            si.nPos = si.nMax - max( si.nPage-1, 0 );
2682            scrollX = si.nPos;
2683         }
2684
2685         if (!(infoPtr->uInternalStatus & TV_HSCROLL))
2686             ShowScrollBar(hwnd, SB_HORZ, TRUE);
2687         infoPtr->uInternalStatus |= TV_HSCROLL;
2688
2689         SetScrollInfo(hwnd, SB_HORZ, &si, TRUE);
2690     }
2691     else
2692     {
2693         if (infoPtr->uInternalStatus & TV_HSCROLL)
2694             ShowScrollBar(hwnd, SB_HORZ, FALSE);
2695         infoPtr->uInternalStatus &= ~TV_HSCROLL;
2696
2697         scrollX = 0;
2698     }
2699
2700     if (infoPtr->scrollX != scrollX)
2701     {
2702         TREEVIEW_HScroll(infoPtr,
2703                          MAKEWPARAM(SB_THUMBPOSITION, scrollX));
2704     }
2705
2706     if (!horz)
2707         infoPtr->uInternalStatus &= ~TV_HSCROLL;
2708 }
2709
2710 /* CtrlSpy doesn't mention this, but CorelDRAW's object manager needs it. */
2711 static LRESULT
2712 TREEVIEW_EraseBackground(TREEVIEW_INFO *infoPtr, HDC hDC)
2713 {
2714     HBRUSH hBrush = CreateSolidBrush(infoPtr->clrBk);
2715     RECT rect;
2716
2717     GetClientRect(infoPtr->hwnd, &rect);
2718     FillRect(hDC, &rect, hBrush);
2719     DeleteObject(hBrush);
2720
2721     return 1;
2722 }
2723
2724 static void
2725 TREEVIEW_Refresh(TREEVIEW_INFO *infoPtr, HDC hdc, RECT *rc)
2726 {
2727     HWND hwnd = infoPtr->hwnd;
2728     RECT rect = *rc;
2729     TREEVIEW_ITEM *wineItem;
2730
2731     if (infoPtr->clientHeight == 0 || infoPtr->clientWidth == 0)
2732     {
2733         TRACE("empty window\n");
2734         return;
2735     }
2736
2737     infoPtr->cdmode = TREEVIEW_SendCustomDrawNotify(infoPtr, CDDS_PREPAINT,
2738                                                     hdc, rect);
2739
2740     if (infoPtr->cdmode == CDRF_SKIPDEFAULT)
2741     {
2742         ReleaseDC(hwnd, hdc);
2743         return;
2744     }
2745
2746     for (wineItem = infoPtr->root->firstChild;
2747          wineItem != NULL;
2748          wineItem = TREEVIEW_GetNextListItem(infoPtr, wineItem))
2749     {
2750         if (ISVISIBLE(wineItem))
2751         {
2752             /* Avoid unneeded calculations */
2753             if (wineItem->rect.top > rect.bottom)
2754                 break;
2755             if (wineItem->rect.bottom < rect.top)
2756                 continue;
2757
2758             TREEVIEW_DrawItem(infoPtr, hdc, wineItem);
2759         }
2760     }
2761
2762     TREEVIEW_UpdateScrollBars(infoPtr);
2763
2764     if (infoPtr->cdmode & CDRF_NOTIFYPOSTPAINT)
2765         infoPtr->cdmode =
2766             TREEVIEW_SendCustomDrawNotify(infoPtr, CDDS_POSTPAINT, hdc, rect);
2767 }
2768
2769 static void
2770 TREEVIEW_Invalidate(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *item)
2771 {
2772     if (item != NULL)
2773         InvalidateRect(infoPtr->hwnd, &item->rect, TRUE);
2774     else
2775         InvalidateRect(infoPtr->hwnd, NULL, TRUE);
2776 }
2777
2778 static LRESULT
2779 TREEVIEW_Paint(TREEVIEW_INFO *infoPtr, WPARAM wParam)
2780 {
2781     HDC hdc;
2782     PAINTSTRUCT ps;
2783     RECT rc;
2784
2785     TRACE("\n");
2786
2787     if (wParam)
2788     {
2789         hdc = (HDC)wParam;
2790         if (!GetUpdateRect(infoPtr->hwnd, &rc, TRUE))
2791         {
2792             HBITMAP hbitmap;
2793             BITMAP bitmap;
2794             hbitmap = GetCurrentObject(hdc, OBJ_BITMAP);
2795             if (!hbitmap) return 0;
2796             GetObjectA(hbitmap, sizeof(BITMAP), &bitmap);
2797             rc.left = 0; rc.top = 0;
2798             rc.right = bitmap.bmWidth;
2799             rc.bottom = bitmap.bmHeight;
2800             TREEVIEW_EraseBackground(infoPtr, (HDC)wParam);
2801         }
2802     }
2803     else
2804     {
2805         hdc = BeginPaint(infoPtr->hwnd, &ps);
2806         rc = ps.rcPaint;
2807     }
2808
2809     if(infoPtr->bRedraw) /* WM_SETREDRAW sets bRedraw */
2810         TREEVIEW_Refresh(infoPtr, hdc, &rc);
2811
2812     if (!wParam)
2813         EndPaint(infoPtr->hwnd, &ps);
2814
2815     return 0;
2816 }
2817
2818
2819 /* Sorting **************************************************************/
2820
2821 /***************************************************************************
2822  * Forward the DPA local callback to the treeview owner callback
2823  */
2824 static INT WINAPI
2825 TREEVIEW_CallBackCompare(TREEVIEW_ITEM *first, TREEVIEW_ITEM *second, LPTVSORTCB pCallBackSort)
2826 {
2827     /* Forward the call to the client-defined callback */
2828     return pCallBackSort->lpfnCompare(first->lParam,
2829                                       second->lParam,
2830                                       pCallBackSort->lParam);
2831 }
2832
2833 /***************************************************************************
2834  * Treeview native sort routine: sort on item text.
2835  */
2836 static INT WINAPI
2837 TREEVIEW_SortOnName(TREEVIEW_ITEM *first, TREEVIEW_ITEM *second,
2838                      TREEVIEW_INFO *infoPtr)
2839 {
2840     TREEVIEW_UpdateDispInfo(infoPtr, first, TVIF_TEXT);
2841     TREEVIEW_UpdateDispInfo(infoPtr, second, TVIF_TEXT);
2842
2843     if(first->pszText && second->pszText)
2844         return lstrcmpiW(first->pszText, second->pszText);
2845     else if(first->pszText)
2846         return -1;
2847     else if(second->pszText)
2848         return 1;
2849     else
2850         return 0;
2851 }
2852
2853 /* Returns the number of physical children belonging to item. */
2854 static INT
2855 TREEVIEW_CountChildren(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *item)
2856 {
2857     INT cChildren = 0;
2858     HTREEITEM hti;
2859
2860     for (hti = item->firstChild; hti != NULL; hti = hti->nextSibling)
2861         cChildren++;
2862
2863     return cChildren;
2864 }
2865
2866 /* Returns a DPA containing a pointer to each physical child of item in
2867  * sibling order. If item has no children, an empty DPA is returned. */
2868 static HDPA
2869 TREEVIEW_BuildChildDPA(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *item)
2870 {
2871     HTREEITEM child = item->firstChild;
2872
2873     HDPA list = DPA_Create(8);
2874     if (list == 0) return NULL;
2875
2876     for (child = item->firstChild; child != NULL; child = child->nextSibling)
2877     {
2878         if (DPA_InsertPtr(list, INT_MAX, child) == -1)
2879         {
2880             DPA_Destroy(list);
2881             return NULL;
2882         }
2883     }
2884
2885     return list;
2886 }
2887
2888 /***************************************************************************
2889  * Setup the treeview structure with regards of the sort method
2890  * and sort the children of the TV item specified in lParam
2891  * fRecurse: currently unused. Should be zero.
2892  * parent: if pSort!=NULL, should equal pSort->hParent.
2893  *         otherwise, item which child items are to be sorted.
2894  * pSort:  sort method info. if NULL, sort on item text.
2895  *         if non-NULL, sort on item's lParam content, and let the
2896  *         application decide what that means. See also TVM_SORTCHILDRENCB.
2897  */
2898
2899 static LRESULT
2900 TREEVIEW_Sort(TREEVIEW_INFO *infoPtr, BOOL fRecurse, HTREEITEM parent,
2901               LPTVSORTCB pSort)
2902 {
2903     INT cChildren;
2904     PFNDPACOMPARE pfnCompare;
2905     LPARAM lpCompare;
2906
2907     /* undocumented feature: TVI_ROOT or NULL means `sort the whole tree' */
2908     if (parent == TVI_ROOT || parent == NULL)
2909         parent = infoPtr->root;
2910
2911     /* Check for a valid handle to the parent item */
2912     if (!TREEVIEW_ValidItem(infoPtr, parent))
2913     {
2914         ERR("invalid item hParent=%x\n", (INT)parent);
2915         return FALSE;
2916     }
2917
2918     if (pSort)
2919     {
2920         pfnCompare = (PFNDPACOMPARE)TREEVIEW_CallBackCompare;
2921         lpCompare = (LPARAM)pSort;
2922     }
2923     else
2924     {
2925         pfnCompare = (PFNDPACOMPARE)TREEVIEW_SortOnName;
2926         lpCompare = (LPARAM)infoPtr;
2927     }
2928
2929     cChildren = TREEVIEW_CountChildren(infoPtr, parent);
2930
2931     /* Make sure there is something to sort */
2932     if (cChildren > 1)
2933     {
2934         /* TREEVIEW_ITEM rechaining */
2935         INT count = 0;
2936         HTREEITEM item = 0;
2937         HTREEITEM nextItem = 0;
2938         HTREEITEM prevItem = 0;
2939
2940         HDPA sortList = TREEVIEW_BuildChildDPA(infoPtr, parent);
2941
2942         if (sortList == NULL)
2943             return FALSE;
2944
2945         /* let DPA sort the list */
2946         DPA_Sort(sortList, pfnCompare, lpCompare);
2947
2948         /* The order of DPA entries has been changed, so fixup the
2949          * nextSibling and prevSibling pointers. */
2950
2951         item = (HTREEITEM)DPA_GetPtr(sortList, count++);
2952         while ((nextItem = (HTREEITEM)DPA_GetPtr(sortList, count++)) != NULL)
2953         {
2954             /* link the two current item toghether */
2955             item->nextSibling = nextItem;
2956             nextItem->prevSibling = item;
2957
2958             if (prevItem == NULL)
2959             {
2960                 /* this is the first item, update the parent */
2961                 parent->firstChild = item;
2962                 item->prevSibling = NULL;
2963             }
2964             else
2965             {
2966                 /* fix the back chaining */
2967                 item->prevSibling = prevItem;
2968             }
2969
2970             /* get ready for the next one */
2971             prevItem = item;
2972             item = nextItem;
2973         }
2974
2975         /* the last item is pointed to by item and never has a sibling */
2976         item->nextSibling = NULL;
2977         parent->lastChild = item;
2978
2979         DPA_Destroy(sortList);
2980
2981         TREEVIEW_VerifyTree(infoPtr);
2982
2983         if (parent->state & TVIS_EXPANDED)
2984         {
2985             int visOrder = infoPtr->firstVisible->visibleOrder;
2986
2987         if (parent == infoPtr->root)
2988             TREEVIEW_RecalculateVisibleOrder(infoPtr, NULL);
2989         else
2990             TREEVIEW_RecalculateVisibleOrder(infoPtr, parent);
2991
2992             if (TREEVIEW_IsChildOf(parent, infoPtr->firstVisible))
2993             {
2994                 TREEVIEW_ITEM *item;
2995
2996                 for (item = infoPtr->root->firstChild; item != NULL;
2997                      item = TREEVIEW_GetNextListItem(infoPtr, item))
2998                 {
2999                     if (item->visibleOrder == visOrder)
3000                         break;
3001                 }
3002
3003                 if (!item) item = parent->firstChild;
3004                 TREEVIEW_SetFirstVisible(infoPtr, item, FALSE);
3005             }
3006
3007             TREEVIEW_Invalidate(infoPtr, NULL);
3008         }
3009
3010         return TRUE;
3011     }
3012     return FALSE;
3013 }
3014
3015
3016 /***************************************************************************
3017  * Setup the treeview structure with regards of the sort method
3018  * and sort the children of the TV item specified in lParam
3019  */
3020 static LRESULT
3021 TREEVIEW_SortChildrenCB(TREEVIEW_INFO *infoPtr, WPARAM wParam, LPTVSORTCB pSort)
3022 {
3023     return TREEVIEW_Sort(infoPtr, wParam, pSort->hParent, pSort);
3024 }
3025
3026
3027 /***************************************************************************
3028  * Sort the children of the TV item specified in lParam.
3029  */
3030 static LRESULT
3031 TREEVIEW_SortChildren(TREEVIEW_INFO *infoPtr, WPARAM wParam, LPARAM lParam)
3032 {
3033     return TREEVIEW_Sort(infoPtr, (BOOL)wParam, (HTREEITEM)lParam, NULL);
3034 }
3035
3036
3037 /* Expansion/Collapse ***************************************************/
3038
3039 static BOOL
3040 TREEVIEW_SendExpanding(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *wineItem,
3041                        UINT action)
3042 {
3043     return !TREEVIEW_SendTreeviewNotify(infoPtr, TVN_ITEMEXPANDINGW, action,
3044                                         TVIF_HANDLE | TVIF_STATE | TVIF_PARAM
3045                                         | TVIF_IMAGE | TVIF_SELECTEDIMAGE,
3046                                         0, wineItem);
3047 }
3048
3049 static VOID
3050 TREEVIEW_SendExpanded(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *wineItem,
3051                       UINT action)
3052 {
3053     TREEVIEW_SendTreeviewNotify(infoPtr, TVN_ITEMEXPANDEDW, action,
3054                                 TVIF_HANDLE | TVIF_STATE | TVIF_PARAM
3055                                 | TVIF_IMAGE | TVIF_SELECTEDIMAGE,
3056                                 0, wineItem);
3057 }
3058
3059
3060 /* This corresponds to TVM_EXPAND with TVE_COLLAPSE.
3061  * bRemoveChildren corresponds to TVE_COLLAPSERESET. */
3062 static BOOL
3063 TREEVIEW_Collapse(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *wineItem,
3064                   BOOL bRemoveChildren, BOOL bUser)
3065 {
3066     UINT action = TVE_COLLAPSE | (bRemoveChildren ? TVE_COLLAPSERESET : 0);
3067     BOOL bSetSelection, bSetFirstVisible;
3068
3069     TRACE("TVE_COLLAPSE %p %s\n", wineItem, TREEVIEW_ItemName(wineItem));
3070
3071     if (!(wineItem->state & TVIS_EXPANDED))
3072         return FALSE;
3073
3074     if (bUser || !(wineItem->state & TVIS_EXPANDEDONCE))
3075         TREEVIEW_SendExpanding(infoPtr, wineItem, action);
3076
3077     if (wineItem->firstChild == NULL)
3078         return FALSE;
3079
3080     wineItem->state &= ~TVIS_EXPANDED;
3081
3082     if (bUser || !(wineItem->state & TVIS_EXPANDEDONCE))
3083         TREEVIEW_SendExpanded(infoPtr, wineItem, action);
3084
3085     bSetSelection = (infoPtr->selectedItem != NULL
3086                      && TREEVIEW_IsChildOf(wineItem, infoPtr->selectedItem));
3087
3088     bSetFirstVisible = (infoPtr->firstVisible != NULL
3089                         && TREEVIEW_IsChildOf(wineItem, infoPtr->firstVisible));
3090
3091     if (bRemoveChildren)
3092     {
3093         INT old_cChildren = wineItem->cChildren;
3094         TRACE("TVE_COLLAPSERESET\n");
3095         wineItem->state &= ~TVIS_EXPANDEDONCE;
3096         TREEVIEW_RemoveAllChildren(infoPtr, wineItem);
3097         wineItem->cChildren = old_cChildren;
3098     }
3099
3100     if (wineItem->firstChild)
3101     {
3102         TREEVIEW_ITEM *item, *sibling;
3103
3104         sibling = TREEVIEW_GetNextListItem(infoPtr, wineItem);
3105
3106         for (item = wineItem->firstChild; item != sibling;
3107              item = TREEVIEW_GetNextListItem(infoPtr, item))
3108         {
3109             item->visibleOrder = -1;
3110         }
3111     }
3112
3113     TREEVIEW_RecalculateVisibleOrder(infoPtr, wineItem);
3114
3115     TREEVIEW_SetFirstVisible(infoPtr, bSetFirstVisible ? wineItem
3116                              : infoPtr->firstVisible, TRUE);
3117
3118     if (bSetSelection)
3119     {
3120         /* Don't call DoSelectItem, it sends notifications. */
3121         if (TREEVIEW_ValidItem(infoPtr, infoPtr->selectedItem))
3122             infoPtr->selectedItem->state &= ~TVIS_SELECTED;
3123         wineItem->state |= TVIS_SELECTED;
3124         infoPtr->selectedItem = wineItem;
3125
3126         TREEVIEW_EnsureVisible(infoPtr, wineItem, FALSE);
3127     }
3128
3129     TREEVIEW_UpdateScrollBars(infoPtr);
3130     TREEVIEW_Invalidate(infoPtr, NULL);
3131
3132     return TRUE;
3133 }
3134
3135 static BOOL
3136 TREEVIEW_Expand(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *wineItem,
3137                 BOOL bExpandPartial, BOOL bUser)
3138 {
3139     TRACE("\n");
3140
3141     if (wineItem->state & TVIS_EXPANDED)
3142        return TRUE;
3143
3144     TRACE("TVE_EXPAND %p %s\n", wineItem, TREEVIEW_ItemName(wineItem));
3145
3146     if (bUser || ((wineItem->cChildren != 0) &&
3147                   !(wineItem->state & TVIS_EXPANDEDONCE)))
3148     {
3149         if (!TREEVIEW_SendExpanding(infoPtr, wineItem, TVE_EXPAND))
3150         {
3151             TRACE("  TVN_ITEMEXPANDING returned TRUE, exiting...\n");
3152             return FALSE;
3153         }
3154
3155         if (!wineItem->firstChild)
3156             return FALSE;
3157
3158         wineItem->state |= TVIS_EXPANDED;
3159         TREEVIEW_SendExpanded(infoPtr, wineItem, TVE_EXPAND);
3160         wineItem->state |= TVIS_EXPANDEDONCE;
3161     }
3162     else
3163     {
3164         if (!wineItem->firstChild)
3165             return FALSE;
3166
3167         /* this item has already been expanded */
3168         wineItem->state |= TVIS_EXPANDED;
3169     }
3170
3171     if (bExpandPartial)
3172         FIXME("TVE_EXPANDPARTIAL not implemented\n");
3173
3174     TREEVIEW_RecalculateVisibleOrder(infoPtr, wineItem);
3175     TREEVIEW_UpdateSubTree(infoPtr, wineItem);
3176     TREEVIEW_UpdateScrollBars(infoPtr);
3177
3178     /* Scroll up so that as many children as possible are visible.
3179      * This looses when expanding causes an HScroll bar to appear, but we
3180      * don't know that yet, so the last item is obscured. */
3181     if (wineItem->firstChild != NULL)
3182     {
3183         int nChildren = wineItem->lastChild->visibleOrder
3184             - wineItem->firstChild->visibleOrder + 1;
3185
3186         int visible_pos = wineItem->visibleOrder
3187             - infoPtr->firstVisible->visibleOrder;
3188
3189         int rows_below = TREEVIEW_GetVisibleCount(infoPtr) - visible_pos - 1;
3190
3191         if (visible_pos > 0 && nChildren > rows_below)
3192         {
3193             int scroll = nChildren - rows_below;
3194
3195             if (scroll > visible_pos)
3196                 scroll = visible_pos;
3197
3198             if (scroll > 0)
3199             {
3200                 TREEVIEW_ITEM *newFirstVisible
3201                     = TREEVIEW_GetListItem(infoPtr, infoPtr->firstVisible,
3202                                            scroll);
3203
3204
3205                 TREEVIEW_SetFirstVisible(infoPtr, newFirstVisible, TRUE);
3206             }
3207         }
3208     }
3209
3210     TREEVIEW_Invalidate(infoPtr, NULL);
3211
3212     return TRUE;
3213 }
3214
3215 static BOOL
3216 TREEVIEW_Toggle(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *wineItem, BOOL bUser)
3217 {
3218     TRACE("\n");
3219
3220     if (wineItem->state & TVIS_EXPANDED)
3221         return TREEVIEW_Collapse(infoPtr, wineItem, FALSE, bUser);
3222     else
3223         return TREEVIEW_Expand(infoPtr, wineItem, FALSE, bUser);
3224 }
3225
3226 static VOID
3227 TREEVIEW_ExpandAll(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *item)
3228 {
3229     TREEVIEW_Expand(infoPtr, item, FALSE, TRUE);
3230
3231     for (item = item->firstChild; item != NULL; item = item->nextSibling)
3232     {
3233         if (TREEVIEW_HasChildren(infoPtr, item))
3234             TREEVIEW_ExpandAll(infoPtr, item);
3235     }
3236 }
3237
3238 /* Note:If the specified item is the child of a collapsed parent item,
3239    the parent's list of child items is (recursively) expanded to reveal the
3240    specified item. This is mentioned for TREEVIEW_SelectItem; don't
3241    know if it also applies here.
3242 */
3243
3244 static LRESULT
3245 TREEVIEW_ExpandMsg(TREEVIEW_INFO *infoPtr, UINT flag, HTREEITEM wineItem)
3246 {
3247     if (!TREEVIEW_ValidItem(infoPtr, wineItem))
3248         return 0;
3249
3250     TRACE("For (%s) item:%d, flags %x, state:%d\n",
3251               TREEVIEW_ItemName(wineItem), flag,
3252               TREEVIEW_GetItemIndex(infoPtr, wineItem), wineItem->state);
3253
3254     switch (flag & TVE_TOGGLE)
3255     {
3256     case TVE_COLLAPSE:
3257         return TREEVIEW_Collapse(infoPtr, wineItem, flag & TVE_COLLAPSERESET,
3258                                  FALSE);
3259
3260     case TVE_EXPAND:
3261         return TREEVIEW_Expand(infoPtr, wineItem, flag & TVE_EXPANDPARTIAL,
3262                                FALSE);
3263
3264     case TVE_TOGGLE:
3265         return TREEVIEW_Toggle(infoPtr, wineItem, TRUE);
3266
3267     default:
3268         return 0;
3269     }
3270
3271 #if 0
3272     TRACE("Exiting, Item %p state is now %d...\n", wineItem, wineItem->state);
3273 #endif
3274 }
3275
3276 /* Hit-Testing **********************************************************/
3277
3278 static TREEVIEW_ITEM *
3279 TREEVIEW_HitTestPoint(TREEVIEW_INFO *infoPtr, POINT pt)
3280 {
3281     TREEVIEW_ITEM *wineItem;
3282     LONG row;
3283
3284     if (!infoPtr->firstVisible)
3285         return NULL;
3286
3287     row = pt.y / infoPtr->uItemHeight + infoPtr->firstVisible->visibleOrder;
3288
3289     for (wineItem = infoPtr->firstVisible; wineItem != NULL;
3290          wineItem = TREEVIEW_GetNextListItem(infoPtr, wineItem))
3291     {
3292         if (row >= wineItem->visibleOrder
3293             && row < wineItem->visibleOrder + wineItem->iIntegral)
3294             break;
3295     }
3296
3297     return wineItem;
3298 }
3299
3300 static LRESULT
3301 TREEVIEW_HitTest(TREEVIEW_INFO *infoPtr, LPTVHITTESTINFO lpht)
3302 {
3303     TREEVIEW_ITEM *wineItem;
3304     RECT rect;
3305     UINT status;
3306     LONG x, y;
3307
3308     lpht->hItem = 0;
3309     GetClientRect(infoPtr->hwnd, &rect);
3310     status = 0;
3311     x = lpht->pt.x;
3312     y = lpht->pt.y;
3313
3314     if (x < rect.left)
3315     {
3316         status |= TVHT_TOLEFT;
3317     }
3318     else if (x > rect.right)
3319     {
3320         status |= TVHT_TORIGHT;
3321     }
3322
3323     if (y < rect.top)
3324     {
3325         status |= TVHT_ABOVE;
3326     }
3327     else if (y > rect.bottom)
3328     {
3329         status |= TVHT_BELOW;
3330     }
3331
3332     if (status)
3333     {
3334         lpht->flags = status;
3335         return (LRESULT)(HTREEITEM)NULL;
3336     }
3337
3338     wineItem = TREEVIEW_HitTestPoint(infoPtr, lpht->pt);
3339     if (!wineItem)
3340     {
3341         lpht->flags = TVHT_NOWHERE;
3342         return (LRESULT)(HTREEITEM)NULL;
3343     }
3344
3345     if (x >= wineItem->textOffset + wineItem->textWidth)
3346     {
3347         lpht->flags = TVHT_ONITEMRIGHT;
3348     }
3349     else if (x >= wineItem->textOffset)
3350     {
3351         lpht->flags = TVHT_ONITEMLABEL;
3352     }
3353     else if (x >= wineItem->imageOffset)
3354     {
3355         lpht->flags = TVHT_ONITEMICON;
3356     }
3357     else if (x >= wineItem->stateOffset)
3358     {
3359         lpht->flags = TVHT_ONITEMSTATEICON;
3360     }
3361     else if (x >= wineItem->linesOffset && infoPtr->dwStyle & TVS_HASBUTTONS)
3362     {
3363         lpht->flags = TVHT_ONITEMBUTTON;
3364     }
3365     else
3366     {
3367         lpht->flags = TVHT_ONITEMINDENT;
3368     }
3369
3370     lpht->hItem = wineItem;
3371     TRACE("(%ld,%ld):result %x\n", lpht->pt.x, lpht->pt.y, lpht->flags);
3372
3373     return (LRESULT)wineItem;
3374 }
3375
3376 /* Item Label Editing ***************************************************/
3377
3378 static LRESULT
3379 TREEVIEW_GetEditControl(TREEVIEW_INFO *infoPtr)
3380 {
3381     return (LRESULT)infoPtr->hwndEdit;
3382 }
3383
3384 static LRESULT CALLBACK
3385 TREEVIEW_Edit_SubclassProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
3386 {
3387     TREEVIEW_INFO *infoPtr = TREEVIEW_GetInfoPtr(GetParent(hwnd));
3388     BOOL bCancel = FALSE;
3389     LRESULT rc;
3390
3391     switch (uMsg)
3392     {
3393     case WM_PAINT:
3394          TRACE("WM_PAINT start\n");
3395          rc = CallWindowProcW(infoPtr->wpEditOrig, hwnd, uMsg, wParam,
3396                                  lParam);
3397          TRACE("WM_PAINT done\n");
3398          return rc;
3399
3400     case WM_KILLFOCUS:
3401         if (infoPtr->bIgnoreEditKillFocus)
3402             return TRUE;
3403         break;
3404
3405     case WM_GETDLGCODE:
3406         return DLGC_WANTARROWS | DLGC_WANTALLKEYS;
3407
3408     case WM_KEYDOWN:
3409         if (wParam == (WPARAM)VK_ESCAPE)
3410         {
3411             bCancel = TRUE;
3412             break;
3413         }
3414         else if (wParam == (WPARAM)VK_RETURN)
3415         {
3416             break;
3417         }
3418
3419         /* fall through */
3420     default:
3421         return CallWindowProcW(infoPtr->wpEditOrig, hwnd, uMsg, wParam, lParam);
3422     }
3423
3424     /* Processing TVN_ENDLABELEDIT message could kill the focus       */
3425     /* eg. Using a messagebox                                         */
3426
3427     infoPtr->bIgnoreEditKillFocus = TRUE;
3428     TREEVIEW_EndEditLabelNow(infoPtr, bCancel || !infoPtr->bLabelChanged);
3429     infoPtr->bIgnoreEditKillFocus = FALSE;
3430
3431     return 0;
3432 }
3433
3434
3435 /* should handle edit control messages here */
3436
3437 static LRESULT
3438 TREEVIEW_Command(TREEVIEW_INFO *infoPtr, WPARAM wParam, LPARAM lParam)
3439 {
3440     TRACE("%x %ld\n", wParam, lParam);
3441
3442     switch (HIWORD(wParam))
3443     {
3444     case EN_UPDATE:
3445         {
3446             /*
3447              * Adjust the edit window size
3448              */
3449             WCHAR buffer[1024];
3450             TREEVIEW_ITEM *editItem = infoPtr->selectedItem;
3451             HDC hdc = GetDC(infoPtr->hwndEdit);
3452             SIZE sz;
3453             int len;
3454             HFONT hFont, hOldFont = 0;
3455
3456             infoPtr->bLabelChanged = TRUE;
3457
3458             len = GetWindowTextW(infoPtr->hwndEdit, buffer, sizeof(buffer));
3459
3460             /* Select font to get the right dimension of the string */
3461             hFont = (HFONT)SendMessageW(infoPtr->hwndEdit, WM_GETFONT, 0, 0);
3462
3463             if (hFont != 0)
3464             {
3465                 hOldFont = SelectObject(hdc, hFont);
3466             }
3467
3468             if (GetTextExtentPoint32W(hdc, buffer, strlenW(buffer), &sz))
3469             {
3470                 TEXTMETRICW textMetric;
3471
3472                 /* Add Extra spacing for the next character */
3473                 GetTextMetricsW(hdc, &textMetric);
3474                 sz.cx += (textMetric.tmMaxCharWidth * 2);
3475
3476                 sz.cx = max(sz.cx, textMetric.tmMaxCharWidth * 3);
3477                 sz.cx = min(sz.cx,
3478                             infoPtr->clientWidth - editItem->textOffset + 2);
3479
3480                 SetWindowPos(infoPtr->hwndEdit,
3481                              HWND_TOP,
3482                              0,
3483                              0,
3484                              sz.cx,
3485                              editItem->rect.bottom - editItem->rect.top + 3,
3486                              SWP_NOMOVE | SWP_DRAWFRAME);
3487             }
3488
3489             if (hFont != 0)
3490             {
3491                 SelectObject(hdc, hOldFont);
3492             }
3493
3494             ReleaseDC(infoPtr->hwnd, hdc);
3495             break;
3496         }
3497
3498     default:
3499         return SendMessageW(infoPtr->hwndNotify, WM_COMMAND, wParam, lParam);
3500     }
3501
3502     return 0;
3503 }
3504
3505 static HWND
3506 TREEVIEW_EditLabel(TREEVIEW_INFO *infoPtr, HTREEITEM hItem)
3507 {
3508     HWND hwnd = infoPtr->hwnd;
3509     HWND hwndEdit;
3510     SIZE sz;
3511     TREEVIEW_ITEM *editItem = hItem;
3512     HINSTANCE hinst = (HINSTANCE)GetWindowLongPtrW(hwnd, GWLP_HINSTANCE);
3513     HDC hdc;
3514     HFONT hOldFont=0;
3515     TEXTMETRICW textMetric;
3516     static const WCHAR EditW[] = {'E','d','i','t',0};
3517
3518     TRACE("%x %p\n", (unsigned)hwnd, hItem);
3519     if (!TREEVIEW_ValidItem(infoPtr, editItem))
3520         return NULL;
3521
3522     if (infoPtr->hwndEdit)
3523         return infoPtr->hwndEdit;
3524
3525     infoPtr->bLabelChanged = FALSE;
3526
3527     /* Make sure that edit item is selected */
3528     TREEVIEW_DoSelectItem(infoPtr, TVGN_CARET, hItem, TVC_UNKNOWN);
3529     TREEVIEW_EnsureVisible(infoPtr, hItem, TRUE);
3530
3531     TREEVIEW_UpdateDispInfo(infoPtr, editItem, TVIF_TEXT);
3532
3533     hdc = GetDC(hwnd);
3534     /* Select the font to get appropriate metric dimensions */
3535     if (infoPtr->hFont != 0)
3536     {
3537         hOldFont = SelectObject(hdc, infoPtr->hFont);
3538     }
3539
3540     /* Get string length in pixels */
3541     GetTextExtentPoint32W(hdc, editItem->pszText, strlenW(editItem->pszText),
3542                           &sz);
3543
3544     /* Add Extra spacing for the next character */
3545     GetTextMetricsW(hdc, &textMetric);
3546     sz.cx += (textMetric.tmMaxCharWidth * 2);
3547
3548     sz.cx = max(sz.cx, textMetric.tmMaxCharWidth * 3);
3549     sz.cx = min(sz.cx, infoPtr->clientWidth - editItem->textOffset + 2);
3550
3551     if (infoPtr->hFont != 0)
3552     {
3553         SelectObject(hdc, hOldFont);
3554     }
3555
3556     ReleaseDC(hwnd, hdc);
3557     hwndEdit = CreateWindowExW(WS_EX_LEFT,
3558                                EditW,
3559                                0,
3560                                WS_CHILD | WS_BORDER | ES_AUTOHSCROLL |
3561                                WS_CLIPSIBLINGS | ES_WANTRETURN |
3562                                ES_LEFT, editItem->textOffset - 2,
3563                                editItem->rect.top - 1, sz.cx + 3,
3564                                editItem->rect.bottom -
3565                                editItem->rect.top + 3, hwnd, 0, hinst, 0);
3566 /* FIXME: (HMENU)IDTVEDIT,pcs->hInstance,0); */
3567
3568     infoPtr->hwndEdit = hwndEdit;
3569
3570     /* Get a 2D border. */
3571     SetWindowLongW(hwndEdit, GWL_EXSTYLE,
3572                    GetWindowLongW(hwndEdit, GWL_EXSTYLE) & ~WS_EX_CLIENTEDGE);
3573     SetWindowLongW(hwndEdit, GWL_STYLE,
3574                    GetWindowLongW(hwndEdit, GWL_STYLE) | WS_BORDER);
3575
3576     SendMessageW(hwndEdit, WM_SETFONT,
3577                  (WPARAM)TREEVIEW_FontForItem(infoPtr, editItem), FALSE);
3578
3579     infoPtr->wpEditOrig = (WNDPROC)SetWindowLongPtrW(hwndEdit, GWLP_WNDPROC,
3580                                                   (DWORD_PTR)
3581                                                   TREEVIEW_Edit_SubclassProc);
3582
3583     if (TREEVIEW_BeginLabelEditNotify(infoPtr, editItem))
3584     {
3585         DestroyWindow(hwndEdit);
3586         infoPtr->hwndEdit = 0;
3587         return NULL;
3588     }
3589
3590     infoPtr->selectedItem = hItem;
3591     SetWindowTextW(hwndEdit, editItem->pszText);
3592     SetFocus(hwndEdit);
3593     SendMessageW(hwndEdit, EM_SETSEL, 0, -1);
3594     ShowWindow(hwndEdit, SW_SHOW);
3595
3596     return hwndEdit;
3597 }
3598
3599
3600 static LRESULT
3601 TREEVIEW_EndEditLabelNow(TREEVIEW_INFO *infoPtr, BOOL bCancel)
3602 {
3603     HWND hwnd = infoPtr->hwnd;
3604     TREEVIEW_ITEM *editedItem = infoPtr->selectedItem;
3605     NMTVDISPINFOW tvdi;
3606     BOOL bCommit;
3607     WCHAR tmpText[1024] = { '\0' };
3608     WCHAR *newText = tmpText;
3609     int iLength = 0;
3610
3611     if (!infoPtr->hwndEdit)
3612         return FALSE;
3613
3614     tvdi.hdr.hwndFrom = hwnd;
3615     tvdi.hdr.idFrom = GetWindowLongPtrW(hwnd, GWLP_ID);
3616     tvdi.hdr.code = get_notifycode(infoPtr, TVN_ENDLABELEDITW);
3617     tvdi.item.mask = 0;
3618     tvdi.item.hItem = editedItem;
3619     tvdi.item.state = editedItem->state;
3620     tvdi.item.lParam = editedItem->lParam;
3621
3622     if (!bCancel)
3623     {
3624         if (!infoPtr->bNtfUnicode)
3625             iLength = GetWindowTextA(infoPtr->hwndEdit, (LPSTR)tmpText, 1023);
3626         else
3627             iLength = GetWindowTextW(infoPtr->hwndEdit, tmpText, 1023);
3628
3629         if (iLength >= 1023)
3630         {
3631             ERR("Insufficient space to retrieve new item label\n");
3632         }
3633
3634         tvdi.item.mask = TVIF_TEXT;
3635         tvdi.item.pszText = tmpText;
3636         tvdi.item.cchTextMax = iLength + 1;
3637     }
3638     else
3639     {
3640         tvdi.item.pszText = NULL;
3641         tvdi.item.cchTextMax = 0;
3642     }
3643
3644     bCommit = (BOOL)TREEVIEW_SendRealNotify(infoPtr,
3645                                  (WPARAM)tvdi.hdr.idFrom, (LPARAM)&tvdi);
3646
3647     if (!bCancel && bCommit)    /* Apply the changes */
3648     {
3649         if (!infoPtr->bNtfUnicode)
3650         {
3651             DWORD len = MultiByteToWideChar( CP_ACP, 0, (LPSTR)tmpText, -1, NULL, 0 );
3652             newText = Alloc(len * sizeof(WCHAR));
3653             MultiByteToWideChar( CP_ACP, 0, (LPSTR)tmpText, -1, newText, len );
3654             iLength = len - 1;
3655         }
3656
3657         if (strcmpW(newText, editedItem->pszText) != 0)
3658         {
3659             if (NULL == ReAlloc(editedItem->pszText, iLength + 1))
3660             {
3661                 ERR("OutOfMemory, cannot allocate space for label\n");
3662                 DestroyWindow(infoPtr->hwndEdit);
3663                 infoPtr->hwndEdit = 0;
3664                 return FALSE;
3665             }
3666             else
3667             {
3668                 editedItem->cchTextMax = iLength + 1;
3669                 strcpyW(editedItem->pszText, newText);
3670             }
3671         }
3672         if(newText != tmpText) Free(newText);
3673     }
3674
3675     ShowWindow(infoPtr->hwndEdit, SW_HIDE);
3676     DestroyWindow(infoPtr->hwndEdit);
3677     infoPtr->hwndEdit = 0;
3678     return TRUE;
3679 }
3680
3681 static LRESULT
3682 TREEVIEW_HandleTimer(TREEVIEW_INFO *infoPtr, WPARAM wParam)
3683 {
3684     if (wParam != TV_EDIT_TIMER)
3685     {
3686         ERR("got unknown timer\n");
3687         return 1;
3688     }
3689
3690     KillTimer(infoPtr->hwnd, TV_EDIT_TIMER);
3691     infoPtr->Timer &= ~TV_EDIT_TIMER_SET;
3692
3693     TREEVIEW_EditLabel(infoPtr, infoPtr->selectedItem);
3694
3695     return 0;
3696 }
3697
3698
3699 /* Mouse Tracking/Drag **************************************************/
3700
3701 /***************************************************************************
3702  * This is quite unusual piece of code, but that's how it's implemented in
3703  * Windows.
3704  */
3705 static LRESULT
3706 TREEVIEW_TrackMouse(TREEVIEW_INFO *infoPtr, POINT pt)
3707 {
3708     INT cxDrag = GetSystemMetrics(SM_CXDRAG);
3709     INT cyDrag = GetSystemMetrics(SM_CYDRAG);
3710     RECT r;
3711     MSG msg;
3712
3713     r.top = pt.y - cyDrag;
3714     r.left = pt.x - cxDrag;
3715     r.bottom = pt.y + cyDrag;
3716     r.right = pt.x + cxDrag;
3717
3718     SetCapture(infoPtr->hwnd);
3719
3720     while (1)
3721     {
3722         if (PeekMessageA(&msg, 0, 0, 0, PM_REMOVE | PM_NOYIELD))
3723         {
3724             if (msg.message == WM_MOUSEMOVE)
3725             {
3726                 pt.x = (short)LOWORD(msg.lParam);
3727                 pt.y = (short)HIWORD(msg.lParam);
3728                 if (PtInRect(&r, pt))
3729                     continue;
3730                 else
3731                 {
3732                     ReleaseCapture();
3733                     return 1;
3734                 }
3735             }
3736             else if (msg.message >= WM_LBUTTONDOWN &&
3737                      msg.message <= WM_RBUTTONDBLCLK)
3738             {
3739                 if (msg.message == WM_RBUTTONUP)
3740                     TREEVIEW_RButtonUp(infoPtr, &pt);
3741                 break;
3742             }
3743
3744             DispatchMessageA(&msg);
3745         }
3746
3747         if (GetCapture() != infoPtr->hwnd)
3748             return 0;
3749     }
3750
3751     ReleaseCapture();
3752     return 0;
3753 }
3754
3755
3756 static LRESULT
3757 TREEVIEW_LButtonDoubleClick(TREEVIEW_INFO *infoPtr, LPARAM lParam)
3758 {
3759     TREEVIEW_ITEM *wineItem;
3760     TVHITTESTINFO hit;
3761
3762     TRACE("\n");
3763     SetFocus(infoPtr->hwnd);
3764
3765     if (infoPtr->Timer & TV_EDIT_TIMER_SET)
3766     {
3767         /* If there is pending 'edit label' event - kill it now */
3768         KillTimer(infoPtr->hwnd, TV_EDIT_TIMER);
3769     }
3770
3771     hit.pt.x = (short)LOWORD(lParam);
3772     hit.pt.y = (short)HIWORD(lParam);
3773
3774     wineItem = (TREEVIEW_ITEM *)TREEVIEW_HitTest(infoPtr, &hit);
3775     if (!wineItem)
3776         return 0;
3777     TRACE("item %d\n", TREEVIEW_GetItemIndex(infoPtr, wineItem));
3778
3779     if (TREEVIEW_SendSimpleNotify(infoPtr, NM_DBLCLK) == FALSE)
3780     {                           /* FIXME! */
3781         switch (hit.flags)
3782         {
3783         case TVHT_ONITEMRIGHT:
3784             /* FIXME: we should not have sent NM_DBLCLK in this case. */
3785             break;
3786
3787         case TVHT_ONITEMINDENT:
3788             if (!(infoPtr->dwStyle & TVS_HASLINES))
3789             {
3790                 break;
3791             }
3792             else
3793             {
3794                 int level = hit.pt.x / infoPtr->uIndent;
3795                 if (!(infoPtr->dwStyle & TVS_LINESATROOT)) level++;
3796
3797                 while (wineItem->iLevel > level)
3798                 {
3799                     wineItem = wineItem->parent;
3800                 }
3801
3802                 /* fall through */
3803             }
3804
3805         case TVHT_ONITEMLABEL:
3806         case TVHT_ONITEMICON:
3807         case TVHT_ONITEMBUTTON:
3808             TREEVIEW_Toggle(infoPtr, wineItem, TRUE);
3809             break;
3810
3811         case TVHT_ONITEMSTATEICON:
3812            if (infoPtr->dwStyle & TVS_CHECKBOXES)
3813                TREEVIEW_ToggleItemState(infoPtr, wineItem);
3814            else
3815                TREEVIEW_Toggle(infoPtr, wineItem, TRUE);
3816            break;
3817         }
3818     }
3819     return TRUE;
3820 }
3821
3822
3823 static LRESULT
3824 TREEVIEW_LButtonDown(TREEVIEW_INFO *infoPtr, LPARAM lParam)
3825 {
3826     HWND hwnd = infoPtr->hwnd;
3827     TVHITTESTINFO ht;
3828     BOOL bTrack, bDoLabelEdit;
3829     HTREEITEM tempItem;
3830
3831     /* If Edit control is active - kill it and return.
3832      * The best way to do it is to set focus to itself.
3833      * Edit control subclassed procedure will automatically call
3834      * EndEditLabelNow.
3835      */
3836     if (infoPtr->hwndEdit)
3837     {
3838         SetFocus(hwnd);
3839         return 0;
3840     }
3841
3842     ht.pt.x = (short)LOWORD(lParam);
3843     ht.pt.y = (short)HIWORD(lParam);
3844
3845     TREEVIEW_HitTest(infoPtr, &ht);
3846     TRACE("item %d\n", TREEVIEW_GetItemIndex(infoPtr, ht.hItem));
3847
3848     /* update focusedItem and redraw both items */
3849     if(ht.hItem && (ht.flags & TVHT_ONITEM))
3850     {
3851         infoPtr->focusedItem = ht.hItem;
3852         InvalidateRect(hwnd, &(((HTREEITEM)(ht.hItem))->rect), TRUE);
3853
3854         if(infoPtr->selectedItem)
3855             InvalidateRect(hwnd, &(infoPtr->selectedItem->rect), TRUE);
3856     }
3857
3858     bTrack = (ht.flags & TVHT_ONITEM)
3859         && !(infoPtr->dwStyle & TVS_DISABLEDRAGDROP);
3860
3861     /*
3862      * If the style allows editing and the node is already selected
3863      * and the click occurred on the item label...
3864      */
3865     bDoLabelEdit = (infoPtr->dwStyle & TVS_EDITLABELS) &&
3866         (ht.flags & TVHT_ONITEMLABEL) && (infoPtr->selectedItem == ht.hItem);
3867
3868     /* Send NM_CLICK right away */
3869     if (!bTrack)
3870         if (TREEVIEW_SendSimpleNotify(infoPtr, NM_CLICK))
3871             goto setfocus;
3872
3873     if (ht.flags & TVHT_ONITEMBUTTON)
3874     {
3875         TREEVIEW_Toggle(infoPtr, ht.hItem, TRUE);
3876         goto setfocus;
3877     }
3878     else if (bTrack)
3879     {   /* if TREEVIEW_TrackMouse == 1 dragging occurred and the cursor left the dragged item's rectangle */
3880         if (TREEVIEW_TrackMouse(infoPtr, ht.pt))
3881         {
3882             TREEVIEW_SendTreeviewDnDNotify(infoPtr, TVN_BEGINDRAGW, ht.hItem, ht.pt);
3883             infoPtr->dropItem = ht.hItem;
3884
3885             /* clean up focusedItem as we dragged and won't select this item */
3886             if(infoPtr->focusedItem)
3887             {
3888                 /* refresh the item that was focused */
3889                 tempItem = infoPtr->focusedItem;
3890                 infoPtr->focusedItem = 0;
3891                 InvalidateRect(infoPtr->hwnd, &tempItem->rect, TRUE);
3892
3893                 /* refresh the selected item to return the filled background */
3894                 InvalidateRect(infoPtr->hwnd, &(infoPtr->selectedItem->rect), TRUE);
3895             }
3896
3897             return 0;
3898         }
3899     }
3900
3901     if (bTrack && TREEVIEW_SendSimpleNotify(infoPtr, NM_CLICK))
3902         goto setfocus;
3903
3904     if (bDoLabelEdit)
3905     {
3906         if (infoPtr->Timer & TV_EDIT_TIMER_SET)
3907             KillTimer(hwnd, TV_EDIT_TIMER);
3908
3909         SetTimer(hwnd, TV_EDIT_TIMER, GetDoubleClickTime(), 0);
3910         infoPtr->Timer |= TV_EDIT_TIMER_SET;
3911     }
3912     else if (ht.flags & (TVHT_ONITEMICON|TVHT_ONITEMLABEL)) /* select the item if the hit was inside of the icon or text */
3913     {
3914         /*
3915          * if we are TVS_SINGLEEXPAND then we want this single click to
3916          * do a bunch of things.
3917          */
3918         if((infoPtr->dwStyle & TVS_SINGLEEXPAND) &&
3919           (infoPtr->hwndEdit == 0))
3920         {
3921             TREEVIEW_ITEM *SelItem;
3922
3923             /*
3924              * Send the notification
3925              */
3926             TREEVIEW_SendTreeviewNotify(infoPtr, TVN_SINGLEEXPAND, TVC_UNKNOWN, TVIF_HANDLE | TVIF_PARAM, ht.hItem, 0);
3927
3928             /*
3929              * Close the previous selection all the way to the root
3930              * as long as the new selection is not a child
3931              */
3932             if((infoPtr->selectedItem)
3933                 && (infoPtr->selectedItem != ht.hItem))
3934             {
3935                 BOOL closeit = TRUE;
3936                 SelItem = ht.hItem;
3937
3938                 /* determine if the hitItem is a child of the currently selected item */
3939                 while(closeit && SelItem && TREEVIEW_ValidItem(infoPtr, SelItem) && (SelItem != infoPtr->root))
3940                 {
3941                     closeit = (SelItem != infoPtr->selectedItem);
3942                     SelItem = SelItem->parent;
3943                 }
3944
3945                 if(closeit)
3946                 {
3947                     if(TREEVIEW_ValidItem(infoPtr, infoPtr->selectedItem))
3948                         SelItem = infoPtr->selectedItem;
3949
3950                     while(SelItem && (SelItem != ht.hItem) && TREEVIEW_ValidItem(infoPtr, SelItem) && (SelItem != infoPtr->root))
3951                     {
3952                         TREEVIEW_Collapse(infoPtr, SelItem, FALSE, FALSE);
3953                         SelItem = SelItem->parent;
3954                     }
3955                 }
3956             }
3957
3958             /*
3959              * Expand the current item
3960              */
3961             TREEVIEW_Expand(infoPtr, ht.hItem, TVE_TOGGLE, FALSE);
3962         }
3963
3964         /* Select the current item */
3965         TREEVIEW_DoSelectItem(infoPtr, TVGN_CARET, ht.hItem, TVC_BYMOUSE);
3966     }
3967     else if (ht.flags & TVHT_ONITEMSTATEICON)
3968     {
3969         /* TVS_CHECKBOXES requires us to toggle the current state */
3970         if (infoPtr->dwStyle & TVS_CHECKBOXES)
3971             TREEVIEW_ToggleItemState(infoPtr, ht.hItem);
3972     }
3973
3974   setfocus:
3975     SetFocus(hwnd);
3976     return 0;
3977 }
3978
3979
3980 static LRESULT
3981 TREEVIEW_RButtonDown(TREEVIEW_INFO *infoPtr, LPARAM lParam)
3982 {
3983     TVHITTESTINFO ht;
3984
3985     if (infoPtr->hwndEdit)
3986     {
3987         SetFocus(infoPtr->hwnd);
3988         return 0;
3989     }
3990
3991     ht.pt.x = (short)LOWORD(lParam);
3992     ht.pt.y = (short)HIWORD(lParam);
3993
3994     TREEVIEW_HitTest(infoPtr, &ht);
3995
3996     if (TREEVIEW_TrackMouse(infoPtr, ht.pt))
3997     {
3998         if (ht.hItem)
3999         {
4000             TREEVIEW_SendTreeviewDnDNotify(infoPtr, TVN_BEGINRDRAGW, ht.hItem, ht.pt);
4001             infoPtr->dropItem = ht.hItem;
4002         }
4003     }
4004     else
4005     {
4006         SetFocus(infoPtr->hwnd);
4007         TREEVIEW_SendSimpleNotify(infoPtr, NM_RCLICK);
4008     }
4009
4010     return 0;
4011 }
4012
4013 static LRESULT
4014 TREEVIEW_RButtonUp(TREEVIEW_INFO *infoPtr, LPPOINT pPt)
4015 {
4016     return 0;
4017 }
4018
4019
4020 static LRESULT
4021 TREEVIEW_CreateDragImage(TREEVIEW_INFO *infoPtr, WPARAM wParam, LPARAM lParam)
4022 {
4023     TREEVIEW_ITEM *dragItem = (HTREEITEM)lParam;
4024     INT cx, cy;
4025     HDC hdc, htopdc;
4026     HWND hwtop;
4027     HBITMAP hbmp, hOldbmp;
4028     SIZE size;
4029     RECT rc;
4030     HFONT hOldFont;
4031
4032     TRACE("\n");
4033
4034     if (!(infoPtr->himlNormal))
4035         return 0;
4036
4037     if (!dragItem || !TREEVIEW_ValidItem(infoPtr, dragItem))
4038         return 0;
4039
4040     TREEVIEW_UpdateDispInfo(infoPtr, dragItem, TVIF_TEXT);
4041
4042     hwtop = GetDesktopWindow();
4043     htopdc = GetDC(hwtop);
4044     hdc = CreateCompatibleDC(htopdc);
4045
4046     hOldFont = SelectObject(hdc, infoPtr->hFont);
4047     GetTextExtentPoint32W(hdc, dragItem->pszText, strlenW(dragItem->pszText),
4048                           &size);
4049     TRACE("%ld %ld %s %d\n", size.cx, size.cy, debugstr_w(dragItem->pszText),
4050           strlenW(dragItem->pszText));
4051     hbmp = CreateCompatibleBitmap(htopdc, size.cx, size.cy);
4052     hOldbmp = SelectObject(hdc, hbmp);
4053
4054     ImageList_GetIconSize(infoPtr->himlNormal, &cx, &cy);
4055     size.cx += cx;
4056     if (cy > size.cy)
4057         size.cy = cy;
4058
4059     infoPtr->dragList = ImageList_Create(size.cx, size.cy, ILC_COLOR, 10, 10);
4060     ImageList_Draw(infoPtr->himlNormal, dragItem->iImage, hdc, 0, 0,
4061                    ILD_NORMAL);
4062
4063 /*
4064  ImageList_GetImageInfo (infoPtr->himlNormal, dragItem->hItem, &iminfo);
4065  ImageList_AddMasked (infoPtr->dragList, iminfo.hbmImage, CLR_DEFAULT);
4066 */
4067
4068 /* draw item text */
4069
4070     SetRect(&rc, cx, 0, size.cx, size.cy);
4071     DrawTextW(hdc, dragItem->pszText, strlenW(dragItem->pszText), &rc,
4072               DT_LEFT);
4073     SelectObject(hdc, hOldFont);
4074     SelectObject(hdc, hOldbmp);
4075
4076     ImageList_Add(infoPtr->dragList, hbmp, 0);
4077
4078     DeleteDC(hdc);
4079     DeleteObject(hbmp);
4080     ReleaseDC(hwtop, htopdc);
4081
4082     return (LRESULT)infoPtr->dragList;
4083 }
4084
4085 /* Selection ************************************************************/
4086
4087 static LRESULT
4088 TREEVIEW_DoSelectItem(TREEVIEW_INFO *infoPtr, INT action, HTREEITEM newSelect,
4089                       INT cause)
4090 {
4091     TREEVIEW_ITEM *prevSelect;
4092     RECT rcFocused;
4093
4094     assert(newSelect == NULL || TREEVIEW_ValidItem(infoPtr, newSelect));
4095
4096     TRACE("Entering item %p (%s), flag %x, cause %x, state %d\n",
4097           newSelect, TREEVIEW_ItemName(newSelect), action, cause,
4098           newSelect ? newSelect->state : 0);
4099
4100     /* reset and redraw focusedItem if focusedItem was set so we don't */
4101     /* have to worry about the previously focused item when we set a new one */
4102     if(infoPtr->focusedItem)
4103     {
4104         rcFocused = (infoPtr->focusedItem)->rect;
4105         infoPtr->focusedItem = 0;
4106         InvalidateRect(infoPtr->hwnd, &rcFocused, TRUE);
4107     }
4108
4109     switch (action)
4110     {
4111     case TVGN_CARET:
4112         prevSelect = infoPtr->selectedItem;
4113
4114         if (prevSelect == newSelect)
4115             return FALSE;
4116
4117         if (TREEVIEW_SendTreeviewNotify(infoPtr,
4118                                         TVN_SELCHANGINGW,
4119                                         cause,
4120                                         TVIF_HANDLE | TVIF_STATE | TVIF_PARAM,
4121                                         prevSelect,
4122                                         newSelect))
4123             return FALSE;
4124
4125         if (prevSelect)
4126             prevSelect->state &= ~TVIS_SELECTED;
4127         if (newSelect)
4128             newSelect->state |= TVIS_SELECTED;
4129
4130         infoPtr->selectedItem = newSelect;
4131
4132         TREEVIEW_EnsureVisible(infoPtr, infoPtr->selectedItem, FALSE);
4133
4134         TREEVIEW_SendTreeviewNotify(infoPtr,
4135                                     TVN_SELCHANGEDW,
4136                                     cause,
4137                                     TVIF_HANDLE | TVIF_STATE | TVIF_PARAM,
4138                                     prevSelect,
4139                                     newSelect);
4140         TREEVIEW_Invalidate(infoPtr, prevSelect);
4141         TREEVIEW_Invalidate(infoPtr, newSelect);
4142         break;
4143
4144     case TVGN_DROPHILITE:
4145         prevSelect = infoPtr->dropItem;
4146
4147         if (prevSelect)
4148             prevSelect->state &= ~TVIS_DROPHILITED;
4149
4150         infoPtr->dropItem = newSelect;
4151
4152         if (newSelect)
4153             newSelect->state |= TVIS_DROPHILITED;
4154
4155         TREEVIEW_Invalidate(infoPtr, prevSelect);
4156         TREEVIEW_Invalidate(infoPtr, newSelect);
4157         break;
4158
4159     case TVGN_FIRSTVISIBLE:
4160         TREEVIEW_EnsureVisible(infoPtr, newSelect, FALSE);
4161         TREEVIEW_SetFirstVisible(infoPtr, newSelect, TRUE);
4162         TREEVIEW_Invalidate(infoPtr, NULL);
4163         break;
4164     }
4165
4166     TRACE("Leaving state %d\n", newSelect ? newSelect->state : 0);
4167     return TRUE;
4168 }
4169
4170 /* FIXME: handle NM_KILLFOCUS etc */
4171 static LRESULT
4172 TREEVIEW_SelectItem(TREEVIEW_INFO *infoPtr, INT wParam, HTREEITEM item)
4173 {
4174     if (item != NULL && !TREEVIEW_ValidItem(infoPtr, item))
4175         return FALSE;
4176
4177     TRACE("%p (%s) %d\n", item, TREEVIEW_ItemName(item), wParam);
4178
4179     if (!TREEVIEW_DoSelectItem(infoPtr, wParam, item, TVC_UNKNOWN))
4180         return FALSE;
4181
4182     return TRUE;
4183 }
4184
4185 /*************************************************************************
4186  *              TREEVIEW_ProcessLetterKeys
4187  *
4188  *  Processes keyboard messages generated by pressing the letter keys
4189  *  on the keyboard.
4190  *  What this does is perform a case insensitive search from the
4191  *  current position with the following quirks:
4192  *  - If two chars or more are pressed in quick succession we search
4193  *    for the corresponding string (e.g. 'abc').
4194  *  - If there is a delay we wipe away the current search string and
4195  *    restart with just that char.
4196  *  - If the user keeps pressing the same character, whether slowly or
4197  *    fast, so that the search string is entirely composed of this
4198  *    character ('aaaaa' for instance), then we search for first item
4199  *    that starting with that character.
4200  *  - If the user types the above character in quick succession, then
4201  *    we must also search for the corresponding string ('aaaaa'), and
4202  *    go to that string if there is a match.
4203  *
4204  * RETURNS
4205  *
4206  *  Zero.
4207  *
4208  * BUGS
4209  *
4210  *  - The current implementation has a list of characters it will
4211  *    accept and it ignores averything else. In particular it will
4212  *    ignore accentuated characters which seems to match what
4213  *    Windows does. But I'm not sure it makes sense to follow
4214  *    Windows there.
4215  *  - We don't sound a beep when the search fails.
4216  *  - The search should start from the focused item, not from the selected
4217  *    item. One reason for this is to allow for multiple selections in trees.
4218  *    But currently infoPtr->focusedItem does not seem very usable.
4219  *
4220  * SEE ALSO
4221  *
4222  *  TREEVIEW_ProcessLetterKeys
4223  */
4224 static INT TREEVIEW_ProcessLetterKeys(
4225     HWND hwnd, /* handle to the window */
4226     WPARAM charCode, /* the character code, the actual character */
4227     LPARAM keyData /* key data */
4228     )
4229 {
4230     TREEVIEW_INFO *infoPtr;
4231     HTREEITEM nItem;
4232     HTREEITEM endidx,idx;
4233     TVITEMEXW item;
4234     WCHAR buffer[MAX_PATH];
4235     DWORD timestamp,elapsed;
4236
4237     /* simple parameter checking */
4238     if (!hwnd || !charCode || !keyData)
4239         return 0;
4240
4241     infoPtr=(TREEVIEW_INFO*)GetWindowLongPtrW(hwnd, 0);
4242     if (!infoPtr)
4243         return 0;
4244
4245     /* only allow the valid WM_CHARs through */
4246     if (!isalnum(charCode) &&
4247         charCode != '.' && charCode != '`' && charCode != '!' &&
4248         charCode != '@' && charCode != '#' && charCode != '$' &&
4249         charCode != '%' && charCode != '^' && charCode != '&' &&
4250         charCode != '*' && charCode != '(' && charCode != ')' &&
4251         charCode != '-' && charCode != '_' && charCode != '+' &&
4252         charCode != '=' && charCode != '\\'&& charCode != ']' &&
4253         charCode != '}' && charCode != '[' && charCode != '{' &&
4254         charCode != '/' && charCode != '?' && charCode != '>' &&
4255         charCode != '<' && charCode != ',' && charCode != '~')
4256         return 0;
4257
4258     /* compute how much time elapsed since last keypress */
4259     timestamp = GetTickCount();
4260     if (timestamp > infoPtr->lastKeyPressTimestamp) {
4261         elapsed=timestamp-infoPtr->lastKeyPressTimestamp;
4262     } else {
4263         elapsed=infoPtr->lastKeyPressTimestamp-timestamp;
4264     }
4265
4266     /* update the search parameters */
4267     infoPtr->lastKeyPressTimestamp=timestamp;
4268     if (elapsed < KEY_DELAY) {
4269         if (infoPtr->nSearchParamLength < sizeof(infoPtr->szSearchParam) / sizeof(WCHAR)) {
4270             infoPtr->szSearchParam[infoPtr->nSearchParamLength++]=charCode;
4271         }
4272         if (infoPtr->charCode != charCode) {
4273             infoPtr->charCode=charCode=0;
4274         }
4275     } else {
4276         infoPtr->charCode=charCode;
4277         infoPtr->szSearchParam[0]=charCode;
4278         infoPtr->nSearchParamLength=1;
4279         /* Redundant with the 1 char string */
4280         charCode=0;
4281     }
4282
4283     /* and search from the current position */
4284     nItem=NULL;
4285     if (infoPtr->selectedItem != NULL) {
4286         endidx=infoPtr->selectedItem;
4287         /* if looking for single character match,
4288          * then we must always move forward
4289          */
4290         if (infoPtr->nSearchParamLength == 1)
4291             idx=TREEVIEW_GetNextListItem(infoPtr,endidx);
4292         else
4293             idx=endidx;
4294     } else {
4295         endidx=NULL;
4296         idx=infoPtr->root->firstChild;
4297     }
4298     do {
4299         if (idx == NULL) {
4300             if (endidx == NULL)
4301                 break;
4302             idx=infoPtr->root->firstChild;
4303         }
4304
4305         /* get item */
4306         ZeroMemory(&item, sizeof(item));
4307         item.mask = TVIF_TEXT;
4308         item.hItem = idx;
4309         item.pszText = buffer;
4310         item.cchTextMax = sizeof(buffer);
4311         TREEVIEW_GetItemT( infoPtr, &item, TRUE );
4312
4313         /* check for a match */
4314         if (strncmpiW(item.pszText,infoPtr->szSearchParam,infoPtr->nSearchParamLength) == 0) {
4315             nItem=idx;
4316             break;
4317         } else if ( (charCode != 0) && (nItem == NULL) &&
4318                     (nItem != infoPtr->selectedItem) &&
4319                     (strncmpiW(item.pszText,infoPtr->szSearchParam,1) == 0) ) {
4320             /* This would work but we must keep looking for a longer match */
4321             nItem=idx;
4322         }
4323         idx=TREEVIEW_GetNextListItem(infoPtr,idx);
4324     } while (idx != endidx);
4325
4326     if (nItem != NULL) {
4327         if (TREEVIEW_DoSelectItem(infoPtr, TVGN_CARET, nItem, TVC_BYKEYBOARD)) {
4328             TREEVIEW_EnsureVisible(infoPtr, nItem, FALSE);
4329         }
4330     }
4331
4332     return 0;
4333 }
4334
4335 /* Scrolling ************************************************************/
4336
4337 static LRESULT
4338 TREEVIEW_EnsureVisible(TREEVIEW_INFO *infoPtr, HTREEITEM item, BOOL bHScroll)
4339 {
4340     int viscount;
4341     BOOL hasFirstVisible = infoPtr->firstVisible != NULL;
4342     HTREEITEM newFirstVisible = NULL;
4343     int visible_pos = -1;
4344
4345     if (!TREEVIEW_ValidItem(infoPtr, item))
4346         return FALSE;
4347
4348     if (!ISVISIBLE(item))
4349     {
4350         /* Expand parents as necessary. */
4351         HTREEITEM parent;
4352
4353         /* see if we are trying to ensure that root is vislble */
4354         if((item != infoPtr->root) && TREEVIEW_ValidItem(infoPtr, item))
4355           parent = item->parent;
4356         else
4357           parent = item; /* this item is the topmost item */
4358
4359         while (parent != infoPtr->root)
4360         {
4361             if (!(parent->state & TVIS_EXPANDED))
4362                 TREEVIEW_Expand(infoPtr, parent, FALSE, FALSE);
4363
4364             parent = parent->parent;
4365         }
4366     }
4367
4368     viscount = TREEVIEW_GetVisibleCount(infoPtr);
4369
4370     TRACE("%p (%s) %ld - %ld viscount(%d)\n", item, TREEVIEW_ItemName(item), item->visibleOrder,
4371         hasFirstVisible ? infoPtr->firstVisible->visibleOrder : -1, viscount);
4372
4373     if (hasFirstVisible)
4374         visible_pos = item->visibleOrder - infoPtr->firstVisible->visibleOrder;
4375
4376     if (visible_pos < 0)
4377     {
4378         /* item is before the start of the list: put it at the top. */
4379         newFirstVisible = item;
4380     }
4381     else if (visible_pos >= viscount
4382              /* Sometimes, before we are displayed, GVC is 0, causing us to
4383               * spuriously scroll up. */
4384              && visible_pos > 0 && !(infoPtr->dwStyle & TVS_NOSCROLL) )
4385     {
4386         /* item is past the end of the list. */
4387         int scroll = visible_pos - viscount;
4388
4389         newFirstVisible = TREEVIEW_GetListItem(infoPtr, infoPtr->firstVisible,
4390                                                scroll + 1);
4391     }
4392
4393     if (bHScroll)
4394     {
4395         /* Scroll window so item's text is visible as much as possible */
4396         /* Calculation of amount of extra space is taken from EditLabel code */
4397         INT pos, x;
4398         TEXTMETRICW textMetric;
4399         HDC hdc = GetWindowDC(infoPtr->hwnd);
4400
4401         x = item->textWidth;
4402
4403         GetTextMetricsW(hdc, &textMetric);
4404         ReleaseDC(infoPtr->hwnd, hdc);
4405
4406         x += (textMetric.tmMaxCharWidth * 2);
4407         x = max(x, textMetric.tmMaxCharWidth * 3);
4408
4409         if (item->textOffset < 0)
4410            pos = item->textOffset;
4411         else if (item->textOffset + x > infoPtr->clientWidth)
4412         {
4413            if (x > infoPtr->clientWidth)
4414               pos = item->textOffset;
4415            else
4416               pos = item->textOffset + x - infoPtr->clientWidth;
4417         }
4418         else
4419            pos = 0;
4420
4421         TREEVIEW_HScroll(infoPtr, MAKEWPARAM(SB_THUMBPOSITION, infoPtr->scrollX + pos));
4422     }
4423
4424     if (newFirstVisible != NULL && newFirstVisible != infoPtr->firstVisible)
4425     {
4426         TREEVIEW_SetFirstVisible(infoPtr, newFirstVisible, TRUE);
4427
4428         return TRUE;
4429     }
4430
4431     return FALSE;
4432 }
4433
4434 static VOID
4435 TREEVIEW_SetFirstVisible(TREEVIEW_INFO *infoPtr,
4436                          TREEVIEW_ITEM *newFirstVisible,
4437                          BOOL bUpdateScrollPos)
4438 {
4439     int gap_size;
4440
4441     TRACE("%p: %s\n", newFirstVisible, TREEVIEW_ItemName(newFirstVisible));
4442
4443     if (newFirstVisible != NULL)
4444     {
4445         /* Prevent an empty gap from appearing at the bottom... */
4446         gap_size = TREEVIEW_GetVisibleCount(infoPtr)
4447             - infoPtr->maxVisibleOrder + newFirstVisible->visibleOrder;
4448
4449         if (gap_size > 0)
4450         {
4451             newFirstVisible = TREEVIEW_GetListItem(infoPtr, newFirstVisible,
4452                                                    -gap_size);
4453
4454             /* ... unless we just don't have enough items. */
4455             if (newFirstVisible == NULL)
4456                 newFirstVisible = infoPtr->root->firstChild;
4457         }
4458     }
4459
4460     if (infoPtr->firstVisible != newFirstVisible)
4461     {
4462         if (infoPtr->firstVisible == NULL || newFirstVisible == NULL)
4463         {
4464             infoPtr->firstVisible = newFirstVisible;
4465             TREEVIEW_Invalidate(infoPtr, NULL);
4466         }
4467         else
4468         {
4469             TREEVIEW_ITEM *item;
4470             int scroll = infoPtr->uItemHeight *
4471                          (infoPtr->firstVisible->visibleOrder
4472                           - newFirstVisible->visibleOrder);
4473
4474             infoPtr->firstVisible = newFirstVisible;
4475
4476             for (item = infoPtr->root->firstChild; item != NULL;
4477                  item = TREEVIEW_GetNextListItem(infoPtr, item))
4478             {
4479                item->rect.top += scroll;
4480                item->rect.bottom += scroll;
4481             }
4482
4483             if (bUpdateScrollPos)
4484                 SetScrollPos(infoPtr->hwnd, SB_VERT,
4485                               newFirstVisible->visibleOrder, TRUE);
4486
4487             ScrollWindowEx(infoPtr->hwnd, 0, scroll, NULL, NULL, NULL, NULL, SW_ERASE | SW_INVALIDATE);
4488         }
4489     }
4490 }
4491
4492 /************************************************************************
4493  * VScroll is always in units of visible items. i.e. we always have a
4494  * visible item aligned to the top of the control. (Unless we have no
4495  * items at all.)
4496  */
4497 static LRESULT
4498 TREEVIEW_VScroll(TREEVIEW_INFO *infoPtr, WPARAM wParam)
4499 {
4500     TREEVIEW_ITEM *oldFirstVisible = infoPtr->firstVisible;
4501     TREEVIEW_ITEM *newFirstVisible = NULL;
4502
4503     int nScrollCode = LOWORD(wParam);
4504
4505     TRACE("wp %x\n", wParam);
4506
4507     if (!(infoPtr->uInternalStatus & TV_VSCROLL))
4508         return 0;
4509
4510     if (infoPtr->hwndEdit)
4511         SetFocus(infoPtr->hwnd);
4512
4513     if (!oldFirstVisible)
4514     {
4515         assert(infoPtr->root->firstChild == NULL);
4516         return 0;
4517     }
4518
4519     switch (nScrollCode)
4520     {
4521     case SB_TOP:
4522         newFirstVisible = infoPtr->root->firstChild;
4523         break;
4524
4525     case SB_BOTTOM:
4526         newFirstVisible = TREEVIEW_GetLastListItem(infoPtr, infoPtr->root);
4527         break;
4528
4529     case SB_LINEUP:
4530         newFirstVisible = TREEVIEW_GetPrevListItem(infoPtr, oldFirstVisible);
4531         break;
4532
4533     case SB_LINEDOWN:
4534         newFirstVisible = TREEVIEW_GetNextListItem(infoPtr, oldFirstVisible);
4535         break;
4536
4537     case SB_PAGEUP:
4538         newFirstVisible = TREEVIEW_GetListItem(infoPtr, oldFirstVisible,
4539                                                -max(1, TREEVIEW_GetVisibleCount(infoPtr)));
4540         break;
4541
4542     case SB_PAGEDOWN:
4543         newFirstVisible = TREEVIEW_GetListItem(infoPtr, oldFirstVisible,
4544                                                max(1, TREEVIEW_GetVisibleCount(infoPtr)));
4545         break;
4546
4547     case SB_THUMBTRACK:
4548     case SB_THUMBPOSITION:
4549         newFirstVisible = TREEVIEW_GetListItem(infoPtr,
4550                                                infoPtr->root->firstChild,
4551                                                (LONG)(SHORT)HIWORD(wParam));
4552         break;
4553
4554     case SB_ENDSCROLL:
4555         return 0;
4556     }
4557
4558     if (newFirstVisible != NULL)
4559     {
4560         if (newFirstVisible != oldFirstVisible)
4561             TREEVIEW_SetFirstVisible(infoPtr, newFirstVisible,
4562                                   nScrollCode != SB_THUMBTRACK);
4563         else if (nScrollCode == SB_THUMBPOSITION)
4564             SetScrollPos(infoPtr->hwnd, SB_VERT,
4565                          newFirstVisible->visibleOrder, TRUE);
4566     }
4567
4568     return 0;
4569 }
4570
4571 static LRESULT
4572 TREEVIEW_HScroll(TREEVIEW_INFO *infoPtr, WPARAM wParam)
4573 {
4574     int maxWidth;
4575     int scrollX = infoPtr->scrollX;
4576     int nScrollCode = LOWORD(wParam);
4577
4578     TRACE("wp %x\n", wParam);
4579
4580     if (!(infoPtr->uInternalStatus & TV_HSCROLL))
4581         return FALSE;
4582
4583     if (infoPtr->hwndEdit)
4584         SetFocus(infoPtr->hwnd);
4585
4586     maxWidth = infoPtr->treeWidth - infoPtr->clientWidth;
4587     /* shall never occur */
4588     if (maxWidth <= 0)
4589     {
4590        scrollX = 0;
4591        goto scroll;
4592     }
4593
4594     switch (nScrollCode)
4595     {
4596     case SB_LINELEFT:
4597         scrollX -= infoPtr->uItemHeight;
4598         break;
4599     case SB_LINERIGHT:
4600         scrollX += infoPtr->uItemHeight;
4601         break;
4602     case SB_PAGELEFT:
4603         scrollX -= infoPtr->clientWidth;
4604         break;
4605     case SB_PAGERIGHT:
4606         scrollX += infoPtr->clientWidth;
4607         break;
4608
4609     case SB_THUMBTRACK:
4610     case SB_THUMBPOSITION:
4611         scrollX = (int)(SHORT)HIWORD(wParam);
4612         break;
4613
4614     case SB_ENDSCROLL:
4615        return 0;
4616     }
4617
4618     if (scrollX > maxWidth)
4619         scrollX = maxWidth;
4620     else if (scrollX < 0)
4621         scrollX = 0;
4622
4623 scroll:
4624     if (scrollX != infoPtr->scrollX)
4625     {
4626         TREEVIEW_ITEM *item;
4627         LONG scroll_pixels = infoPtr->scrollX - scrollX;
4628
4629         for (item = infoPtr->root->firstChild; item != NULL;
4630              item = TREEVIEW_GetNextListItem(infoPtr, item))
4631         {
4632            item->linesOffset += scroll_pixels;
4633            item->stateOffset += scroll_pixels;
4634            item->imageOffset += scroll_pixels;
4635            item->textOffset  += scroll_pixels;
4636         }
4637
4638         ScrollWindow(infoPtr->hwnd, scroll_pixels, 0, NULL, NULL);
4639         infoPtr->scrollX = scrollX;
4640         UpdateWindow(infoPtr->hwnd);
4641     }
4642
4643     if (nScrollCode != SB_THUMBTRACK)
4644        SetScrollPos(infoPtr->hwnd, SB_HORZ, scrollX, TRUE);
4645
4646     return 0;
4647 }
4648
4649 static LRESULT
4650 TREEVIEW_MouseWheel(TREEVIEW_INFO *infoPtr, WPARAM wParam)
4651 {
4652     short gcWheelDelta;
4653     UINT pulScrollLines = 3;
4654
4655     if (infoPtr->firstVisible == NULL)
4656         return TRUE;
4657
4658     SystemParametersInfoW(SPI_GETWHEELSCROLLLINES, 0, &pulScrollLines, 0);
4659
4660     gcWheelDelta = -(short)HIWORD(wParam);
4661     pulScrollLines *= (gcWheelDelta / WHEEL_DELTA);
4662
4663     if (abs(gcWheelDelta) >= WHEEL_DELTA && pulScrollLines)
4664     {
4665         int newDy = infoPtr->firstVisible->visibleOrder + pulScrollLines;
4666         int maxDy = infoPtr->maxVisibleOrder;
4667
4668         if (newDy > maxDy)
4669             newDy = maxDy;
4670
4671         if (newDy < 0)
4672             newDy = 0;
4673
4674         TREEVIEW_VScroll(infoPtr, MAKEWPARAM(SB_THUMBPOSITION, newDy));
4675     }
4676     return TRUE;
4677 }
4678
4679 /* Create/Destroy *******************************************************/
4680
4681 static LRESULT
4682 TREEVIEW_Create(HWND hwnd, const CREATESTRUCTW *lpcs)
4683 {
4684     static const WCHAR szDisplayW[] = { 'D','I','S','P','L','A','Y','\0' };
4685     RECT rcClient;
4686     TREEVIEW_INFO *infoPtr;
4687
4688     TRACE("wnd %p, style %lx\n", hwnd, GetWindowLongW(hwnd, GWL_STYLE));
4689
4690     infoPtr = (TREEVIEW_INFO *)Alloc(sizeof(TREEVIEW_INFO));
4691
4692     if (infoPtr == NULL)
4693     {
4694         ERR("could not allocate info memory!\n");
4695         return 0;
4696     }
4697
4698     SetWindowLongPtrW(hwnd, 0, (DWORD_PTR)infoPtr);
4699
4700     infoPtr->hwnd = hwnd;
4701     infoPtr->dwStyle = GetWindowLongW(hwnd, GWL_STYLE);
4702     infoPtr->uInternalStatus = 0;
4703     infoPtr->Timer = 0;
4704     infoPtr->uNumItems = 0;
4705     infoPtr->cdmode = 0;
4706     infoPtr->uScrollTime = 300; /* milliseconds */
4707     infoPtr->bRedraw = TRUE;
4708
4709     GetClientRect(hwnd, &rcClient);
4710
4711     /* No scroll bars yet. */
4712     infoPtr->clientWidth = rcClient.right;
4713     infoPtr->clientHeight = rcClient.bottom;
4714
4715     infoPtr->treeWidth = 0;
4716     infoPtr->treeHeight = 0;
4717
4718     infoPtr->uIndent = MINIMUM_INDENT;
4719     infoPtr->selectedItem = 0;
4720     infoPtr->focusedItem = 0;
4721     /* hotItem? */
4722     infoPtr->firstVisible = 0;
4723     infoPtr->maxVisibleOrder = 0;
4724     infoPtr->dropItem = 0;
4725     infoPtr->insertMarkItem = 0;
4726     infoPtr->insertBeforeorAfter = 0;
4727     /* dragList */
4728
4729     infoPtr->scrollX = 0;
4730
4731     infoPtr->clrBk = GetSysColor(COLOR_WINDOW);
4732     infoPtr->clrText = -1;      /* use system color */
4733     infoPtr->clrLine = RGB(128, 128, 128);
4734     infoPtr->clrInsertMark = GetSysColor(COLOR_BTNTEXT);
4735
4736     /* hwndToolTip */
4737
4738     infoPtr->hwndEdit = 0;
4739     infoPtr->wpEditOrig = NULL;
4740     infoPtr->bIgnoreEditKillFocus = FALSE;
4741     infoPtr->bLabelChanged = FALSE;
4742
4743     infoPtr->himlNormal = NULL;
4744     infoPtr->himlState = NULL;
4745     infoPtr->normalImageWidth = 0;
4746     infoPtr->normalImageHeight = 0;
4747     infoPtr->stateImageWidth = 0;
4748     infoPtr->stateImageHeight = 0;
4749
4750     infoPtr->items = DPA_Create(16);
4751
4752     infoPtr->hFont = GetStockObject(DEFAULT_GUI_FONT);
4753     infoPtr->hBoldFont = TREEVIEW_CreateBoldFont(infoPtr->hFont);
4754
4755     infoPtr->uItemHeight = TREEVIEW_NaturalHeight(infoPtr);
4756
4757     infoPtr->root = TREEVIEW_AllocateItem(infoPtr);
4758     infoPtr->root->state = TVIS_EXPANDED;
4759     infoPtr->root->iLevel = -1;
4760     infoPtr->root->visibleOrder = -1;
4761
4762     infoPtr->hwndNotify = lpcs->hwndParent;
4763 #if 0
4764     infoPtr->bTransparent = ( GetWindowLongW( hwnd, GWL_STYLE) & TBSTYLE_FLAT);
4765 #endif
4766
4767     infoPtr->hwndToolTip = 0;
4768
4769     infoPtr->bNtfUnicode = IsWindowUnicode (hwnd);
4770
4771     /* Determine what type of notify should be issued */
4772     /* sets infoPtr->bNtfUnicode */
4773     TREEVIEW_NotifyFormat(infoPtr, infoPtr->hwndNotify, NF_REQUERY);
4774
4775     if (!(infoPtr->dwStyle & TVS_NOTOOLTIPS))
4776         infoPtr->hwndToolTip = COMCTL32_CreateToolTip(hwnd);
4777
4778     if (infoPtr->dwStyle & TVS_CHECKBOXES)
4779     {
4780         RECT rc;
4781         HBITMAP hbm, hbmOld;
4782         HDC hdc,hdcScreen;
4783         int nIndex;
4784
4785         infoPtr->himlState =
4786             ImageList_Create(16, 16, ILC_COLOR | ILC_MASK, 3, 0);
4787
4788         hdcScreen = CreateDCW(szDisplayW, NULL, NULL, NULL);
4789
4790         /* Create a coloured bitmap compatible with the screen depth
4791            because checkboxes are not black&white */
4792         hdc = CreateCompatibleDC(hdcScreen);
4793         hbm = CreateCompatibleBitmap(hdcScreen, 48, 16);
4794         hbmOld = SelectObject(hdc, hbm);
4795
4796         rc.left  = 0;   rc.top    = 0;
4797         rc.right = 48;  rc.bottom = 16;
4798         FillRect(hdc, &rc, (HBRUSH)(COLOR_WINDOW+1));
4799
4800         rc.left  = 18;   rc.top    = 2;
4801         rc.right = 30;   rc.bottom = 14;
4802         DrawFrameControl(hdc, &rc, DFC_BUTTON,
4803                           DFCS_BUTTONCHECK|DFCS_FLAT);
4804
4805         rc.left  = 34;   rc.right  = 46;
4806         DrawFrameControl(hdc, &rc, DFC_BUTTON,
4807                           DFCS_BUTTONCHECK|DFCS_FLAT|DFCS_CHECKED);
4808
4809         SelectObject(hdc, hbmOld);
4810         nIndex = ImageList_AddMasked(infoPtr->himlState, hbm,
4811                                       GetSysColor(COLOR_WINDOW));
4812         TRACE("checkbox index %d\n", nIndex);
4813
4814         DeleteObject(hbm);
4815         DeleteDC(hdc);
4816         DeleteDC(hdcScreen);
4817
4818         infoPtr->stateImageWidth = 16;
4819         infoPtr->stateImageHeight = 16;
4820     }
4821     return 0;
4822 }
4823
4824
4825 static LRESULT
4826 TREEVIEW_Destroy(TREEVIEW_INFO *infoPtr)
4827 {
4828     TRACE("\n");
4829
4830     TREEVIEW_RemoveTree(infoPtr);
4831
4832     /* tool tip is automatically destroyed: we are its owner */
4833
4834     /* Restore original wndproc */
4835     if (infoPtr->hwndEdit)
4836         SetWindowLongPtrW(infoPtr->hwndEdit, GWLP_WNDPROC,
4837                        (DWORD_PTR)infoPtr->wpEditOrig);
4838
4839     /* Deassociate treeview from the window before doing anything drastic. */
4840     SetWindowLongPtrW(infoPtr->hwnd, 0, (DWORD_PTR)NULL);
4841
4842     DeleteObject(infoPtr->hBoldFont);
4843     Free(infoPtr);
4844
4845     return 0;
4846 }
4847
4848 /* Miscellaneous Messages ***********************************************/
4849
4850 static LRESULT
4851 TREEVIEW_ScrollKeyDown(TREEVIEW_INFO *infoPtr, WPARAM key)
4852 {
4853     static const struct
4854     {
4855         unsigned char code;
4856     }
4857     scroll[] =
4858     {
4859 #define SCROLL_ENTRY(dir, code) { ((dir) << 7) | (code) }
4860         SCROLL_ENTRY(SB_VERT, SB_PAGEUP),       /* VK_PRIOR */
4861         SCROLL_ENTRY(SB_VERT, SB_PAGEDOWN),     /* VK_NEXT */
4862         SCROLL_ENTRY(SB_VERT, SB_BOTTOM),       /* VK_END */
4863         SCROLL_ENTRY(SB_VERT, SB_TOP),          /* VK_HOME */
4864         SCROLL_ENTRY(SB_HORZ, SB_LINEUP),       /* VK_LEFT */
4865         SCROLL_ENTRY(SB_VERT, SB_LINEUP),       /* VK_UP */
4866         SCROLL_ENTRY(SB_HORZ, SB_LINEDOWN),     /* VK_RIGHT */
4867         SCROLL_ENTRY(SB_VERT, SB_LINEDOWN)      /* VK_DOWN */
4868 #undef SCROLL_ENTRY
4869     };
4870
4871     if (key >= VK_PRIOR && key <= VK_DOWN)
4872     {
4873         unsigned char code = scroll[key - VK_PRIOR].code;
4874
4875         (((code & (1 << 7)) == (SB_HORZ << 7))
4876          ? TREEVIEW_HScroll
4877          : TREEVIEW_VScroll)(infoPtr, code & 0x7F);
4878     }
4879
4880     return 0;
4881 }
4882
4883 /************************************************************************
4884  *        TREEVIEW_KeyDown
4885  *
4886  * VK_UP       Move selection to the previous non-hidden item.
4887  * VK_DOWN     Move selection to the next non-hidden item.
4888  * VK_HOME     Move selection to the first item.
4889  * VK_END      Move selection to the last item.
4890  * VK_LEFT     If expanded then collapse, otherwise move to parent.
4891  * VK_RIGHT    If collapsed then expand, otherwise move to first child.
4892  * VK_ADD      Expand.
4893  * VK_SUBTRACT Collapse.
4894  * VK_MULTIPLY Expand all.
4895  * VK_PRIOR    Move up GetVisibleCount items.
4896  * VK_NEXT     Move down GetVisibleCount items.
4897  * VK_BACK     Move to parent.
4898  * CTRL-Left,Right,Up,Down,PgUp,PgDown,Home,End: Scroll without changing selection
4899  */
4900 static LRESULT
4901 TREEVIEW_KeyDown(TREEVIEW_INFO *infoPtr, WPARAM wParam)
4902 {
4903     /* If it is non-NULL and different, it will be selected and visible. */
4904     TREEVIEW_ITEM *newSelection = NULL;
4905
4906     TREEVIEW_ITEM *prevItem = infoPtr->selectedItem;
4907
4908     TRACE("%x\n", wParam);
4909
4910     if (prevItem == NULL)
4911         return FALSE;
4912
4913     if (GetAsyncKeyState(VK_CONTROL) & 0x8000)
4914         return TREEVIEW_ScrollKeyDown(infoPtr, wParam);
4915
4916     switch (wParam)
4917     {
4918     case VK_UP:
4919         newSelection = TREEVIEW_GetPrevListItem(infoPtr, prevItem);
4920         if (!newSelection)
4921             newSelection = infoPtr->root->firstChild;
4922         break;
4923
4924     case VK_DOWN:
4925         newSelection = TREEVIEW_GetNextListItem(infoPtr, prevItem);
4926         break;
4927
4928     case VK_HOME:
4929         newSelection = infoPtr->root->firstChild;
4930         break;
4931
4932     case VK_END:
4933         newSelection = TREEVIEW_GetLastListItem(infoPtr, infoPtr->root);
4934         break;
4935
4936     case VK_LEFT:
4937         if (prevItem->state & TVIS_EXPANDED)
4938         {
4939             TREEVIEW_Collapse(infoPtr, prevItem, FALSE, TRUE);
4940         }
4941         else if (prevItem->parent != infoPtr->root)
4942         {
4943             newSelection = prevItem->parent;
4944         }
4945         break;
4946
4947     case VK_RIGHT:
4948         if (TREEVIEW_HasChildren(infoPtr, prevItem))
4949         {
4950             if (!(prevItem->state & TVIS_EXPANDED))
4951                 TREEVIEW_Expand(infoPtr, prevItem, FALSE, TRUE);
4952             else
4953             {
4954                 newSelection = prevItem->firstChild;
4955             }
4956         }
4957
4958         break;
4959
4960     case VK_MULTIPLY:
4961         TREEVIEW_ExpandAll(infoPtr, prevItem);
4962         break;
4963
4964     case VK_ADD:
4965         if (!(prevItem->state & TVIS_EXPANDED))
4966             TREEVIEW_Expand(infoPtr, prevItem, FALSE, TRUE);
4967         break;
4968
4969     case VK_SUBTRACT:
4970         if (prevItem->state & TVIS_EXPANDED)
4971             TREEVIEW_Collapse(infoPtr, prevItem, FALSE, TRUE);
4972         break;
4973
4974     case VK_PRIOR:
4975         newSelection
4976             = TREEVIEW_GetListItem(infoPtr, prevItem,
4977                                    -TREEVIEW_GetVisibleCount(infoPtr));
4978         break;
4979
4980     case VK_NEXT:
4981         newSelection
4982             = TREEVIEW_GetListItem(infoPtr, prevItem,
4983                                    TREEVIEW_GetVisibleCount(infoPtr));
4984         break;
4985
4986     case VK_BACK:
4987         newSelection = prevItem->parent;
4988         if (newSelection == infoPtr->root)
4989             newSelection = NULL;
4990         break;
4991
4992     case VK_SPACE:
4993         if (infoPtr->dwStyle & TVS_CHECKBOXES)
4994             TREEVIEW_ToggleItemState(infoPtr, prevItem);
4995         break;
4996     }
4997
4998     if (newSelection && newSelection != prevItem)
4999     {
5000         if (TREEVIEW_DoSelectItem(infoPtr, TVGN_CARET, newSelection,
5001                                   TVC_BYKEYBOARD))
5002         {
5003             TREEVIEW_EnsureVisible(infoPtr, newSelection, FALSE);
5004         }
5005     }
5006
5007     return FALSE;
5008 }
5009
5010 static LRESULT
5011 TREEVIEW_Notify(TREEVIEW_INFO *infoPtr, WPARAM wParam, LPARAM lParam)
5012 {
5013     LPNMHDR lpnmh = (LPNMHDR)lParam;
5014
5015     if (lpnmh->code == PGN_CALCSIZE) {
5016         LPNMPGCALCSIZE lppgc = (LPNMPGCALCSIZE)lParam;
5017
5018         if (lppgc->dwFlag == PGF_CALCWIDTH) {
5019             lppgc->iWidth = infoPtr->treeWidth;
5020             TRACE("got PGN_CALCSIZE, returning horz size = %ld, client=%ld\n",
5021                   infoPtr->treeWidth, infoPtr->clientWidth);
5022         }
5023         else {
5024             lppgc->iHeight = infoPtr->treeHeight;
5025             TRACE("got PGN_CALCSIZE, returning vert size = %ld, client=%ld\n",
5026                   infoPtr->treeHeight, infoPtr->clientHeight);
5027         }
5028         return 0;
5029     }
5030     return DefWindowProcA(infoPtr->hwnd, WM_NOTIFY, wParam, lParam);
5031 }
5032
5033 static INT TREEVIEW_NotifyFormat (TREEVIEW_INFO *infoPtr, HWND hwndFrom, UINT nCommand)
5034 {
5035     INT format;
5036
5037     TRACE("(hwndFrom=%p, nCommand=%d)\n", hwndFrom, nCommand);
5038
5039     if (nCommand != NF_REQUERY) return 0;
5040
5041     format = SendMessageW(hwndFrom, WM_NOTIFYFORMAT, (WPARAM)infoPtr->hwnd, NF_QUERY);
5042     TRACE("format=%d\n", format);
5043
5044     if (format != NFR_ANSI && format != NFR_UNICODE) return 0;
5045
5046     infoPtr->bNtfUnicode = (format == NFR_UNICODE);
5047
5048     return format;
5049 }
5050
5051 static LRESULT
5052 TREEVIEW_Size(TREEVIEW_INFO *infoPtr, WPARAM wParam, LPARAM lParam)
5053 {
5054     if (wParam == SIZE_RESTORED)
5055     {
5056         infoPtr->clientWidth  = (short)LOWORD(lParam);
5057         infoPtr->clientHeight = (short)HIWORD(lParam);
5058
5059         TREEVIEW_RecalculateVisibleOrder(infoPtr, NULL);
5060         TREEVIEW_SetFirstVisible(infoPtr, infoPtr->firstVisible, TRUE);
5061         TREEVIEW_UpdateScrollBars(infoPtr);
5062     }
5063     else
5064     {
5065         FIXME("WM_SIZE flag %x %lx not handled\n", wParam, lParam);
5066     }
5067
5068     TREEVIEW_Invalidate(infoPtr, NULL);
5069     return 0;
5070 }
5071
5072 static LRESULT
5073 TREEVIEW_StyleChanged(TREEVIEW_INFO *infoPtr, WPARAM wParam, LPARAM lParam)
5074 {
5075     TRACE("(%x %lx)\n", wParam, lParam);
5076
5077     if (wParam == GWL_STYLE)
5078     {
5079        DWORD dwNewStyle = ((LPSTYLESTRUCT)lParam)->styleNew;
5080
5081        /* we have to take special care about tooltips */
5082        if ((infoPtr->dwStyle ^ dwNewStyle) & TVS_NOTOOLTIPS)
5083        {
5084           if (infoPtr->dwStyle & TVS_NOTOOLTIPS)
5085           {
5086               infoPtr->hwndToolTip = COMCTL32_CreateToolTip(infoPtr->hwnd);
5087               TRACE("\n");
5088           }
5089           else
5090           {
5091              DestroyWindow(infoPtr->hwndToolTip);
5092              infoPtr->hwndToolTip = 0;
5093           }
5094        }
5095
5096        infoPtr->dwStyle = dwNewStyle;
5097     }
5098
5099     TREEVIEW_UpdateSubTree(infoPtr, infoPtr->root);
5100     TREEVIEW_UpdateScrollBars(infoPtr);
5101     TREEVIEW_Invalidate(infoPtr, NULL);
5102
5103     return 0;
5104 }
5105
5106 static LRESULT
5107 TREEVIEW_SetFocus(TREEVIEW_INFO *infoPtr)
5108 {
5109     TRACE("\n");
5110
5111     if (!infoPtr->selectedItem)
5112     {
5113         TREEVIEW_DoSelectItem(infoPtr, TVGN_CARET, infoPtr->firstVisible,
5114                               TVC_UNKNOWN);
5115     }
5116
5117     TREEVIEW_SendSimpleNotify(infoPtr, NM_SETFOCUS);
5118     TREEVIEW_Invalidate(infoPtr, infoPtr->selectedItem);
5119     return 0;
5120 }
5121
5122 static LRESULT
5123 TREEVIEW_KillFocus(TREEVIEW_INFO *infoPtr)
5124 {
5125     TRACE("\n");
5126
5127     TREEVIEW_SendSimpleNotify(infoPtr, NM_KILLFOCUS);
5128     TREEVIEW_Invalidate(infoPtr, infoPtr->selectedItem);
5129     return 0;
5130 }
5131
5132
5133 static LRESULT WINAPI
5134 TREEVIEW_WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
5135 {
5136     TREEVIEW_INFO *infoPtr = TREEVIEW_GetInfoPtr(hwnd);
5137
5138     TRACE("hwnd %p msg %04x wp=%08x lp=%08lx\n", hwnd, uMsg, wParam, lParam);
5139
5140     if (infoPtr) TREEVIEW_VerifyTree(infoPtr);
5141     else
5142     {
5143         if (uMsg == WM_CREATE)
5144             TREEVIEW_Create(hwnd, (LPCREATESTRUCTW)lParam);
5145         else
5146             goto def;
5147     }
5148
5149     switch (uMsg)
5150     {
5151     case TVM_CREATEDRAGIMAGE:
5152         return TREEVIEW_CreateDragImage(infoPtr, wParam, lParam);
5153
5154     case TVM_DELETEITEM:
5155         return TREEVIEW_DeleteItem(infoPtr, (HTREEITEM)lParam);
5156
5157     case TVM_EDITLABELA:
5158         return (LRESULT)TREEVIEW_EditLabel(infoPtr, (HTREEITEM)lParam);
5159
5160     case TVM_EDITLABELW:
5161         return (LRESULT)TREEVIEW_EditLabel(infoPtr, (HTREEITEM)lParam);
5162
5163     case TVM_ENDEDITLABELNOW:
5164         return TREEVIEW_EndEditLabelNow(infoPtr, (BOOL)wParam);
5165
5166     case TVM_ENSUREVISIBLE:
5167         return TREEVIEW_EnsureVisible(infoPtr, (HTREEITEM)lParam, TRUE);
5168
5169     case TVM_EXPAND:
5170         return TREEVIEW_ExpandMsg(infoPtr, (UINT)wParam, (HTREEITEM)lParam);
5171
5172     case TVM_GETBKCOLOR:
5173         return TREEVIEW_GetBkColor(infoPtr);
5174
5175     case TVM_GETCOUNT:
5176         return TREEVIEW_GetCount(infoPtr);
5177
5178     case TVM_GETEDITCONTROL:
5179         return TREEVIEW_GetEditControl(infoPtr);
5180
5181     case TVM_GETIMAGELIST:
5182         return TREEVIEW_GetImageList(infoPtr, wParam);
5183
5184     case TVM_GETINDENT:
5185         return TREEVIEW_GetIndent(infoPtr);
5186
5187     case TVM_GETINSERTMARKCOLOR:
5188         return TREEVIEW_GetInsertMarkColor(infoPtr);
5189
5190     case TVM_GETISEARCHSTRINGA:
5191         FIXME("Unimplemented msg TVM_GETISEARCHSTRINGA\n");
5192         return 0;
5193
5194     case TVM_GETISEARCHSTRINGW:
5195         FIXME("Unimplemented msg TVM_GETISEARCHSTRINGW\n");
5196         return 0;
5197
5198     case TVM_GETITEMA:
5199         return TREEVIEW_GetItemT(infoPtr, (LPTVITEMEXW)lParam, FALSE);
5200
5201     case TVM_GETITEMW:
5202         return TREEVIEW_GetItemT(infoPtr, (LPTVITEMEXW)lParam, TRUE);
5203
5204     case TVM_GETITEMHEIGHT:
5205         return TREEVIEW_GetItemHeight(infoPtr);
5206
5207     case TVM_GETITEMRECT:
5208         return TREEVIEW_GetItemRect(infoPtr, (BOOL)wParam, (LPRECT)lParam);
5209
5210     case TVM_GETITEMSTATE:
5211         return TREEVIEW_GetItemState(infoPtr, (HTREEITEM)wParam, (UINT)lParam);
5212
5213     case TVM_GETLINECOLOR:
5214         return TREEVIEW_GetLineColor(infoPtr);
5215
5216     case TVM_GETNEXTITEM:
5217         return TREEVIEW_GetNextItem(infoPtr, (UINT)wParam, (HTREEITEM)lParam);
5218
5219     case TVM_GETSCROLLTIME:
5220         return TREEVIEW_GetScrollTime(infoPtr);
5221
5222     case TVM_GETTEXTCOLOR:
5223         return TREEVIEW_GetTextColor(infoPtr);
5224
5225     case TVM_GETTOOLTIPS:
5226         return TREEVIEW_GetToolTips(infoPtr);
5227
5228     case TVM_GETUNICODEFORMAT:
5229         return TREEVIEW_GetUnicodeFormat(infoPtr);
5230
5231     case TVM_GETVISIBLECOUNT:
5232         return TREEVIEW_GetVisibleCount(infoPtr);
5233
5234     case TVM_HITTEST:
5235         return TREEVIEW_HitTest(infoPtr, (LPTVHITTESTINFO)lParam);
5236
5237     case TVM_INSERTITEMA:
5238         return TREEVIEW_InsertItemT(infoPtr, (LPTVINSERTSTRUCTW)lParam, FALSE);
5239
5240     case TVM_INSERTITEMW:
5241         return TREEVIEW_InsertItemT(infoPtr, (LPTVINSERTSTRUCTW)lParam, TRUE);
5242
5243     case TVM_SELECTITEM:
5244         return TREEVIEW_SelectItem(infoPtr, (INT)wParam, (HTREEITEM)lParam);
5245
5246     case TVM_SETBKCOLOR:
5247         return TREEVIEW_SetBkColor(infoPtr, (COLORREF)lParam);
5248
5249     case TVM_SETIMAGELIST:
5250         return TREEVIEW_SetImageList(infoPtr, wParam, (HIMAGELIST)lParam);
5251
5252     case TVM_SETINDENT:
5253         return TREEVIEW_SetIndent(infoPtr, (UINT)wParam);
5254
5255     case TVM_SETINSERTMARK:
5256         return TREEVIEW_SetInsertMark(infoPtr, (BOOL)wParam, (HTREEITEM)lParam);
5257
5258     case TVM_SETINSERTMARKCOLOR:
5259         return TREEVIEW_SetInsertMarkColor(infoPtr, (COLORREF)lParam);
5260
5261     case TVM_SETITEMA:
5262         return TREEVIEW_SetItemT(infoPtr, (LPTVITEMEXW)lParam, FALSE);
5263
5264     case TVM_SETITEMW:
5265         return TREEVIEW_SetItemT(infoPtr, (LPTVITEMEXW)lParam, TRUE);
5266
5267     case TVM_SETLINECOLOR:
5268         return TREEVIEW_SetLineColor(infoPtr, (COLORREF)lParam);
5269
5270     case TVM_SETITEMHEIGHT:
5271         return TREEVIEW_SetItemHeight(infoPtr, (INT)(SHORT)wParam);
5272
5273     case TVM_SETSCROLLTIME:
5274         return TREEVIEW_SetScrollTime(infoPtr, (UINT)wParam);
5275
5276     case TVM_SETTEXTCOLOR:
5277         return TREEVIEW_SetTextColor(infoPtr, (COLORREF)lParam);
5278
5279     case TVM_SETTOOLTIPS:
5280         return TREEVIEW_SetToolTips(infoPtr, (HWND)wParam);
5281
5282     case TVM_SETUNICODEFORMAT:
5283         return TREEVIEW_SetUnicodeFormat(infoPtr, (BOOL)wParam);
5284
5285     case TVM_SORTCHILDREN:
5286         return TREEVIEW_SortChildren(infoPtr, wParam, lParam);
5287
5288     case TVM_SORTCHILDRENCB:
5289         return TREEVIEW_SortChildrenCB(infoPtr, wParam, (LPTVSORTCB)lParam);
5290
5291     case WM_CHAR:
5292         return TREEVIEW_ProcessLetterKeys( hwnd, wParam, lParam );
5293
5294     case WM_COMMAND:
5295         return TREEVIEW_Command(infoPtr, wParam, lParam);
5296
5297     case WM_DESTROY:
5298         return TREEVIEW_Destroy(infoPtr);
5299
5300         /* WM_ENABLE */
5301
5302     case WM_ERASEBKGND:
5303         return TREEVIEW_EraseBackground(infoPtr, (HDC)wParam);
5304
5305     case WM_GETDLGCODE:
5306         return DLGC_WANTARROWS | DLGC_WANTCHARS;
5307
5308     case WM_GETFONT:
5309         return TREEVIEW_GetFont(infoPtr);
5310
5311     case WM_HSCROLL:
5312         return TREEVIEW_HScroll(infoPtr, wParam);
5313
5314     case WM_KEYDOWN:
5315         return TREEVIEW_KeyDown(infoPtr, wParam);
5316
5317     case WM_KILLFOCUS:
5318         return TREEVIEW_KillFocus(infoPtr);
5319
5320     case WM_LBUTTONDBLCLK:
5321         return TREEVIEW_LButtonDoubleClick(infoPtr, lParam);
5322
5323     case WM_LBUTTONDOWN:
5324         return TREEVIEW_LButtonDown(infoPtr, lParam);
5325
5326         /* WM_MBUTTONDOWN */
5327
5328         /* WM_MOUSEMOVE */
5329
5330     case WM_NOTIFY:
5331         return TREEVIEW_Notify(infoPtr, wParam, lParam);
5332
5333     case WM_NOTIFYFORMAT:
5334         return TREEVIEW_NotifyFormat(infoPtr, (HWND)wParam, (UINT)lParam);
5335
5336     case WM_PAINT:
5337         return TREEVIEW_Paint(infoPtr, wParam);
5338
5339         /* WM_PRINTCLIENT */
5340
5341     case WM_RBUTTONDOWN:
5342         return TREEVIEW_RButtonDown(infoPtr, lParam);
5343
5344     case WM_SETFOCUS:
5345         return TREEVIEW_SetFocus(infoPtr);
5346
5347     case WM_SETFONT:
5348         return TREEVIEW_SetFont(infoPtr, (HFONT)wParam, (BOOL)lParam);
5349
5350     case WM_SETREDRAW:
5351         return TREEVIEW_SetRedraw(infoPtr, wParam, lParam);
5352
5353     case WM_SIZE:
5354         return TREEVIEW_Size(infoPtr, wParam, lParam);
5355
5356     case WM_STYLECHANGED:
5357         return TREEVIEW_StyleChanged(infoPtr, wParam, lParam);
5358
5359         /* WM_SYSCOLORCHANGE */
5360
5361         /* WM_SYSKEYDOWN */
5362
5363     case WM_TIMER:
5364         return TREEVIEW_HandleTimer(infoPtr, wParam);
5365
5366     case WM_VSCROLL:
5367         return TREEVIEW_VScroll(infoPtr, wParam);
5368
5369         /* WM_WININICHANGE */
5370
5371     case WM_MOUSEWHEEL:
5372         if (wParam & (MK_SHIFT | MK_CONTROL))
5373             goto def;
5374         return TREEVIEW_MouseWheel(infoPtr, wParam);
5375
5376     case WM_DRAWITEM:
5377         TRACE("drawItem\n");
5378         goto def;
5379
5380     default:
5381         /* This mostly catches MFC and Delphi messages. :( */
5382         if ((uMsg >= WM_USER) && (uMsg < WM_APP))
5383             TRACE("Unknown msg %04x wp=%08x lp=%08lx\n", uMsg, wParam, lParam);
5384 def:
5385         return DefWindowProcA(hwnd, uMsg, wParam, lParam);
5386     }
5387     return 0;
5388 }
5389
5390
5391 /* Class Registration ***************************************************/
5392
5393 VOID
5394 TREEVIEW_Register(void)
5395 {
5396     WNDCLASSA wndClass;
5397
5398     TRACE("\n");
5399
5400     ZeroMemory(&wndClass, sizeof(WNDCLASSA));
5401     wndClass.style = CS_GLOBALCLASS | CS_DBLCLKS;
5402     wndClass.lpfnWndProc = (WNDPROC)TREEVIEW_WindowProc;
5403     wndClass.cbClsExtra = 0;
5404     wndClass.cbWndExtra = sizeof(TREEVIEW_INFO *);
5405
5406     wndClass.hCursor = LoadCursorA(0, (LPSTR)IDC_ARROW);
5407     wndClass.hbrBackground = 0;
5408     wndClass.lpszClassName = WC_TREEVIEWA;
5409
5410     RegisterClassA(&wndClass);
5411 }
5412
5413
5414 VOID
5415 TREEVIEW_Unregister(void)
5416 {
5417     UnregisterClassA(WC_TREEVIEWA, NULL);
5418 }
5419
5420
5421 /* Tree Verification ****************************************************/
5422
5423 #ifdef NDEBUG
5424 static inline void
5425 TREEVIEW_VerifyChildren(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *item);
5426
5427 static inline void TREEVIEW_VerifyItemCommon(TREEVIEW_INFO *infoPtr,
5428                                              TREEVIEW_ITEM *item)
5429 {
5430     assert(infoPtr != NULL);
5431     assert(item != NULL);
5432
5433     /* both NULL, or both non-null */
5434     assert((item->firstChild == NULL) == (item->lastChild == NULL));
5435
5436     assert(item->firstChild != item);
5437     assert(item->lastChild != item);
5438
5439     if (item->firstChild)
5440     {
5441         assert(item->firstChild->parent == item);
5442         assert(item->firstChild->prevSibling == NULL);
5443     }
5444
5445     if (item->lastChild)
5446     {
5447         assert(item->lastChild->parent == item);
5448         assert(item->lastChild->nextSibling == NULL);
5449     }
5450
5451     assert(item->nextSibling != item);
5452     if (item->nextSibling)
5453     {
5454         assert(item->nextSibling->parent == item->parent);
5455         assert(item->nextSibling->prevSibling == item);
5456     }
5457
5458     assert(item->prevSibling != item);
5459     if (item->prevSibling)
5460     {
5461         assert(item->prevSibling->parent == item->parent);
5462         assert(item->prevSibling->nextSibling == item);
5463     }
5464 }
5465
5466 static inline void
5467 TREEVIEW_VerifyItem(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *item)
5468 {
5469     assert(item != NULL);
5470
5471     assert(item->parent != NULL);
5472     assert(item->parent != item);
5473     assert(item->iLevel == item->parent->iLevel + 1);
5474
5475     assert(DPA_GetPtrIndex(infoPtr->items, item) != -1);
5476
5477     TREEVIEW_VerifyItemCommon(infoPtr, item);
5478
5479     TREEVIEW_VerifyChildren(infoPtr, item);
5480 }
5481
5482 static inline void
5483 TREEVIEW_VerifyChildren(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *item)
5484 {
5485     TREEVIEW_ITEM *child;
5486     assert(item != NULL);
5487
5488     for (child = item->firstChild; child != NULL; child = child->nextSibling)
5489         TREEVIEW_VerifyItem(infoPtr, child);
5490 }
5491
5492 static inline void
5493 TREEVIEW_VerifyRoot(TREEVIEW_INFO *infoPtr)
5494 {
5495     TREEVIEW_ITEM *root = infoPtr->root;
5496
5497     assert(root != NULL);
5498     assert(root->iLevel == -1);
5499     assert(root->parent == NULL);
5500     assert(root->prevSibling == NULL);
5501
5502     TREEVIEW_VerifyItemCommon(infoPtr, root);
5503
5504     TREEVIEW_VerifyChildren(infoPtr, root);
5505 }
5506
5507 static void
5508 TREEVIEW_VerifyTree(TREEVIEW_INFO *infoPtr)
5509 {
5510     assert(infoPtr != NULL);
5511
5512     TREEVIEW_VerifyRoot(infoPtr);
5513 }
5514 #endif