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