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