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