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