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