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