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