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