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