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