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