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