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