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