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