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