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