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