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