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