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