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