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