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