~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~ [ freetext search ] ~ [ file search ] ~

Wine Cross Reference
wine/dlls/comctl32/treeview.c

Version: ~ [ wine-1.1.38 ] ~ [ wine-1.1.37 ] ~ [ wine-1.1.36 ] ~ [ wine-1.1.35 ] ~ [ wine-1.1.34 ] ~ [ wine-1.1.33 ] ~ [ wine-1.1.32 ] ~ [ wine-1.1.31 ] ~ [ wine-1.1.30 ] ~ [ wine-1.1.29 ] ~ [ wine-1.1.28 ] ~ [ wine-1.1.27 ] ~ [ wine-1.1.26 ] ~ [ wine-1.1.25 ] ~ [ wine-1.1.24 ] ~ [ wine-1.1.23 ] ~ [ wine-1.1.22 ] ~ [ wine-1.1.21 ] ~ [ wine-1.1.20 ] ~ [ wine-1.1.19 ] ~ [ wine-1.1.18 ] ~ [ wine-1.1.17 ] ~ [ wine-1.1.16 ] ~ [ wine-1.1.15 ] ~ [ wine-1.1.14 ] ~ [ wine-1.1.13 ] ~ [ wine-1.1.12 ] ~ [ wine-1.1.11 ] ~ [ wine-1.1.10 ] ~ [ wine-1.1.9 ] ~ [ wine-1.1.8 ] ~ [ wine-1.1.7 ] ~ [ wine-1.0.1 ] ~ [ wine-1.1.6 ] ~ [ wine-1.1.5 ] ~ [ wine-1.1.4 ] ~ [ wine-1.1.3 ] ~ [ wine-1.1.2 ] ~ [ wine-1.1.1 ] ~ [ wine-1.1.0 ] ~ [ wine-1.0 ] ~

  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       cChildren;
 80   LPARAM    lParam;
 81   int       iIntegral;      /* item height multiplier (1 is normal) */
 82   int       iLevel;         /* indentation level:0=root level */
 83   HTREEITEM parent;         /* handle to parent or 0 if at root */
 84   HTREEITEM firstChild;     /* handle to first child or 0 if no child */
 85   HTREEITEM lastChild;
 86   HTREEITEM prevSibling;    /* handle to prev item in list, 0 if first */
 87   HTREEITEM nextSibling;    /* handle to next item in list, 0 if last */
 88   RECT      rect;
 89   LONG      linesOffset;
 90   LONG      stateOffset;
 91   LONG      imageOffset;
 92   LONG      textOffset;
 93   LONG      textWidth;      /* horizontal text extent for pszText */
 94   LONG      visibleOrder;   /* visible ordering, 0 is first visible item */
 95 } TREEVIEW_ITEM;
 96 
 97 
 98 typedef struct tagTREEVIEW_INFO
 99 {
100   HWND          hwnd;
101   HWND          hwndNotify;     /* Owner window to send notifications to */
102   DWORD         dwStyle;
103   HTREEITEM     root;
104   UINT          uInternalStatus;
105   INT           Timer;
106   UINT          uNumItems;      /* number of valid TREEVIEW_ITEMs */
107   INT           cdmode;         /* last custom draw setting */
108   UINT          uScrollTime;    /* max. time for scrolling in milliseconds */
109   BOOL          bRedraw;        /* if FALSE we validate but don't redraw in TREEVIEW_Paint() */
110 
111   UINT          uItemHeight;    /* item height */
112   BOOL          bHeightSet;
113 
114   LONG          clientWidth;    /* width of control window */
115   LONG          clientHeight;   /* height of control window */
116 
117   LONG          treeWidth;      /* width of visible tree items */
118   LONG          treeHeight;     /* height of visible tree items */
119 
120   UINT          uIndent;        /* indentation in pixels */
121   HTREEITEM     selectedItem;   /* handle to selected item or 0 if none */
122   HTREEITEM     hotItem;        /* handle currently under cursor, 0 if none */
123   HTREEITEM     focusedItem;    /* item that was under the cursor when WM_LBUTTONDOWN was received */
124   HTREEITEM     editItem;       /* item being edited with builtin edit box */
125 
126   HTREEITEM     firstVisible;   /* handle to first visible item */
127   LONG          maxVisibleOrder;
128   HTREEITEM     dropItem;       /* handle to item selected by drag cursor */
129   HTREEITEM     insertMarkItem; /* item after which insertion mark is placed */
130   BOOL          insertBeforeorAfter; /* flag used by TVM_SETINSERTMARK */
131   HIMAGELIST    dragList;       /* Bitmap of dragged item */
132   LONG          scrollX;
133   COLORREF      clrBk;
134   COLORREF      clrText;
135   COLORREF      clrLine;
136   COLORREF      clrInsertMark;
137   HFONT         hFont;
138   HFONT         hDefaultFont;
139   HFONT         hBoldFont;
140   HFONT         hUnderlineFont;
141   HCURSOR       hcurHand;
142   HWND          hwndToolTip;
143 
144   HWND          hwndEdit;
145   WNDPROC       wpEditOrig;     /* orig window proc for subclassing edit */
146   BOOL          bIgnoreEditKillFocus;
147   BOOL          bLabelChanged;
148 
149   BOOL          bNtfUnicode;    /* TRUE if should send NOTIFY with W */
150   HIMAGELIST    himlNormal;
151   int           normalImageHeight;
152   int           normalImageWidth;
153   HIMAGELIST    himlState;
154   int           stateImageHeight;
155   int           stateImageWidth;
156   HDPA          items;
157 
158   DWORD lastKeyPressTimestamp;
159   WPARAM charCode;
160   INT nSearchParamLength;
161   WCHAR szSearchParam[ MAX_PATH ];
162 } TREEVIEW_INFO;
163 
164 
165 /******** Defines that TREEVIEW_ProcessLetterKeys uses ****************/
166 #define KEY_DELAY       450
167 
168 /* bitflags for infoPtr->uInternalStatus */
169 
170 #define TV_HSCROLL      0x01    /* treeview too large to fit in window */
171 #define TV_VSCROLL      0x02    /* (horizontal/vertical) */
172 #define TV_LDRAG                0x04    /* Lbutton pushed to start drag */
173 #define TV_LDRAGGING    0x08    /* Lbutton pushed, mouse moved. */
174 #define TV_RDRAG                0x10    /* ditto Rbutton */
175 #define TV_RDRAGGING    0x20
176 
177 /* bitflags for infoPtr->timer */
178 
179 #define TV_EDIT_TIMER    2
180 #define TV_EDIT_TIMER_SET 2
181 
182 #define TEXT_CALLBACK_SIZE 260
183 
184 #define TREEVIEW_LEFT_MARGIN 8
185 
186 #define MINIMUM_INDENT 19
187 
188 #define CALLBACK_MASK_ALL (TVIF_TEXT|TVIF_CHILDREN|TVIF_IMAGE|TVIF_SELECTEDIMAGE)
189 
190 #define STATEIMAGEINDEX(x) (((x) >> 12) & 0x0f)
191 #define OVERLAYIMAGEINDEX(x) (((x) >> 8) & 0x0f)
192 #define ISVISIBLE(x)         ((x)->visibleOrder >= 0)
193 
194 #define GETLINECOLOR(x) ((x) == CLR_DEFAULT ? comctl32_color.clrGrayText   : (x))
195 #define GETBKCOLOR(x)   ((x) == CLR_NONE    ? comctl32_color.clrWindow     : (x))
196 #define GETTXTCOLOR(x)  ((x) == CLR_NONE    ? comctl32_color.clrWindowText : (x))
197 #define GETINSCOLOR(x)  ((x) == CLR_DEFAULT ? comctl32_color.clrBtnText    : (x))
198 
199 static const WCHAR themeClass[] = { 'T','r','e','e','v','i','e','w',0 };
200 
201 
202 typedef VOID (*TREEVIEW_ItemEnumFunc)(TREEVIEW_INFO *, TREEVIEW_ITEM *,LPVOID);
203 
204 
205 static VOID TREEVIEW_Invalidate(const TREEVIEW_INFO *, const TREEVIEW_ITEM *);
206 
207 static LRESULT TREEVIEW_DoSelectItem(TREEVIEW_INFO *, INT, HTREEITEM, INT);
208 static VOID TREEVIEW_SetFirstVisible(TREEVIEW_INFO *, TREEVIEW_ITEM *, BOOL);
209 static LRESULT TREEVIEW_EnsureVisible(TREEVIEW_INFO *, HTREEITEM, BOOL);
210 static LRESULT TREEVIEW_RButtonUp(const TREEVIEW_INFO *, const POINT *);
211 static LRESULT TREEVIEW_EndEditLabelNow(TREEVIEW_INFO *infoPtr, BOOL bCancel);
212 static VOID TREEVIEW_UpdateScrollBars(TREEVIEW_INFO *infoPtr);
213 static LRESULT TREEVIEW_HScroll(TREEVIEW_INFO *, WPARAM);
214 
215 /* Random Utilities *****************************************************/
216 
217 #ifndef NDEBUG
218 static inline void
219 TREEVIEW_VerifyTree(TREEVIEW_INFO *infoPtr)
220 {
221     (void)infoPtr;
222 }
223 #else
224 /* The definition is at the end of the file. */
225 static void TREEVIEW_VerifyTree(TREEVIEW_INFO *infoPtr);
226 #endif
227 
228 /* Returns the treeview private data if hwnd is a treeview.
229  * Otherwise returns an undefined value. */
230 static TREEVIEW_INFO *
231 TREEVIEW_GetInfoPtr(HWND hwnd)
232 {
233     return (TREEVIEW_INFO *)GetWindowLongPtrW(hwnd, 0);
234 }
235 
236 /* Don't call this. Nothing wants an item index. */
237 static inline int
238 TREEVIEW_GetItemIndex(const TREEVIEW_INFO *infoPtr, HTREEITEM handle)
239 {
240     return DPA_GetPtrIndex(infoPtr->items, handle);
241 }
242 
243 /* Checks if item has changed and needs to be redrawn */
244 static inline BOOL item_changed (const TREEVIEW_ITEM *tiOld, const TREEVIEW_ITEM *tiNew,
245                                  const TVITEMEXW *tvChange)
246 {
247     /* Number of children has changed */
248     if ((tvChange->mask & TVIF_CHILDREN) && (tiOld->cChildren != tiNew->cChildren))
249         return TRUE;
250 
251     /* Image has changed and it's not a callback */
252     if ((tvChange->mask & TVIF_IMAGE) && (tiOld->iImage != tiNew->iImage) &&
253         tiNew->iImage != I_IMAGECALLBACK)
254         return TRUE;
255 
256     /* Selected image has changed and it's not a callback */
257     if ((tvChange->mask & TVIF_SELECTEDIMAGE) && (tiOld->iSelectedImage != tiNew->iSelectedImage) &&
258         tiNew->iSelectedImage != I_IMAGECALLBACK)
259         return TRUE;
260 
261     /* Text has changed and it's not a callback */
262     if ((tvChange->mask & TVIF_TEXT) && (tiOld->pszText != tiNew->pszText) &&
263         tiNew->pszText != LPSTR_TEXTCALLBACKW)
264         return TRUE;
265 
266     /* Indent has changed */
267     if ((tvChange->mask & TVIF_INTEGRAL) && (tiOld->iIntegral != tiNew->iIntegral))
268         return TRUE;
269 
270     /* Item state has changed */
271     if ((tvChange->mask & TVIF_STATE) && ((tiOld->state ^ tiNew->state) & tvChange->stateMask ))
272         return TRUE;
273 
274     return FALSE;
275 }
276 
277 /***************************************************************************
278  * This method checks that handle is an item for this tree.
279  */
280 static BOOL
281 TREEVIEW_ValidItem(const TREEVIEW_INFO *infoPtr, HTREEITEM handle)
282 {
283     if (TREEVIEW_GetItemIndex(infoPtr, handle) == -1)
284     {
285         TRACE("invalid item %p\n", handle);
286         return FALSE;
287     }
288     else
289         return TRUE;
290 }
291 
292 static HFONT
293 TREEVIEW_CreateBoldFont(HFONT hOrigFont)
294 {
295     LOGFONTW font;
296 
297     GetObjectW(hOrigFont, sizeof(font), &font);
298     font.lfWeight = FW_BOLD;
299     return CreateFontIndirectW(&font);
300 }
301 
302 static HFONT
303 TREEVIEW_CreateUnderlineFont(HFONT hOrigFont)
304 {
305     LOGFONTW font;
306 
307     GetObjectW(hOrigFont, sizeof(font), &font);
308     font.lfUnderline = TRUE;
309     return CreateFontIndirectW(&font);
310 }
311 
312 static inline HFONT
313 TREEVIEW_FontForItem(const TREEVIEW_INFO *infoPtr, const TREEVIEW_ITEM *item)
314 {
315     if ((infoPtr->dwStyle & TVS_TRACKSELECT) && (item == infoPtr->hotItem))
316         return infoPtr->hUnderlineFont;
317     if (item->state & TVIS_BOLD)
318         return infoPtr->hBoldFont;
319     return infoPtr->hFont;
320 }
321 
322 /* for trace/debugging purposes only */
323 static const char *
324 TREEVIEW_ItemName(const TREEVIEW_ITEM *item)
325 {
326     if (item == NULL) return "<null item>";
327     if (item->pszText == LPSTR_TEXTCALLBACKW) return "<callback>";
328     if (item->pszText == NULL) return "<null>";
329     return debugstr_w(item->pszText);
330 }
331 
332 /* An item is not a child of itself. */
333 static BOOL
334 TREEVIEW_IsChildOf(const TREEVIEW_ITEM *parent, const TREEVIEW_ITEM *child)
335 {
336     do
337     {
338         child = child->parent;
339         if (child == parent) return TRUE;
340     } while (child != NULL);
341 
342     return FALSE;
343 }
344 
345 
346 /* Tree Traversal *******************************************************/
347 
348 /***************************************************************************
349  * This method returns the last expanded sibling or child child item
350  * of a tree node
351  */
352 static TREEVIEW_ITEM *
353 TREEVIEW_GetLastListItem(const TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *wineItem)
354 {
355     if (!wineItem)
356        return NULL;
357 
358     while (wineItem->lastChild)
359     {
360        if (wineItem->state & TVIS_EXPANDED)
361           wineItem = wineItem->lastChild;
362        else
363           break;
364     }
365 
366     if (wineItem == infoPtr->root)
367         return NULL;
368 
369     return wineItem;
370 }
371 
372 /***************************************************************************
373  * This method returns the previous non-hidden item in the list not
374  * considering the tree hierarchy.
375  */
376 static TREEVIEW_ITEM *
377 TREEVIEW_GetPrevListItem(const TREEVIEW_INFO *infoPtr, const TREEVIEW_ITEM *tvItem)
378 {
379     if (tvItem->prevSibling)
380     {
381         /* This item has a prevSibling, get the last item in the sibling's tree. */
382         TREEVIEW_ITEM *upItem = tvItem->prevSibling;
383 
384         if ((upItem->state & TVIS_EXPANDED) && upItem->lastChild != NULL)
385             return TREEVIEW_GetLastListItem(infoPtr, upItem->lastChild);
386         else
387             return upItem;
388     }
389     else
390     {
391         /* this item does not have a prevSibling, get the parent */
392         return (tvItem->parent != infoPtr->root) ? tvItem->parent : NULL;
393     }
394 }
395 
396 
397 /***************************************************************************
398  * This method returns the next physical item in the treeview not
399  * considering the tree hierarchy.
400  */
401 static TREEVIEW_ITEM *
402 TREEVIEW_GetNextListItem(const TREEVIEW_INFO *infoPtr, const TREEVIEW_ITEM *tvItem)
403 {
404     /*
405      * If this item has children and is expanded, return the first child
406      */
407     if ((tvItem->state & TVIS_EXPANDED) && tvItem->firstChild != NULL)
408     {
409         return tvItem->firstChild;
410     }
411 
412 
413     /*
414      * try to get the sibling
415      */
416     if (tvItem->nextSibling)
417         return tvItem->nextSibling;
418 
419     /*
420      * Otherwise, get the parent's sibling.
421      */
422     while (tvItem->parent)
423     {
424         tvItem = tvItem->parent;
425 
426         if (tvItem->nextSibling)
427             return tvItem->nextSibling;
428     }
429 
430     return NULL;
431 }
432 
433 /***************************************************************************
434  * This method returns the nth item starting at the given item.  It returns
435  * the last item (or first) we we run out of items.
436  *
437  * Will scroll backward if count is <0.
438  *             forward if count is >0.
439  */
440 static TREEVIEW_ITEM *
441 TREEVIEW_GetListItem(const TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *wineItem,
442                      LONG count)
443 {
444     TREEVIEW_ITEM *(*next_item)(const TREEVIEW_INFO *, const TREEVIEW_ITEM *);
445     TREEVIEW_ITEM *previousItem;
446 
447     assert(wineItem != NULL);
448 
449     if (count > 0)
450     {
451         next_item = TREEVIEW_GetNextListItem;
452     }
453     else if (count < 0)
454     {
455         count = -count;
456         next_item = TREEVIEW_GetPrevListItem;
457     }
458     else
459         return wineItem;
460 
461     do
462     {
463         previousItem = wineItem;
464         wineItem = next_item(infoPtr, wineItem);
465 
466     } while (--count && wineItem != NULL);
467 
468 
469     return wineItem ? wineItem : previousItem;
470 }
471 
472 /* Notifications ************************************************************/
473 
474 static INT get_notifycode(const TREEVIEW_INFO *infoPtr, INT code)
475 {
476     if (!infoPtr->bNtfUnicode) {
477         switch (code) {
478         case TVN_SELCHANGINGW:    return TVN_SELCHANGINGA;
479         case TVN_SELCHANGEDW:     return TVN_SELCHANGEDA;
480         case TVN_GETDISPINFOW:    return TVN_GETDISPINFOA;
481         case TVN_SETDISPINFOW:    return TVN_SETDISPINFOA;
482         case TVN_ITEMEXPANDINGW:  return TVN_ITEMEXPANDINGA;
483         case TVN_ITEMEXPANDEDW:   return TVN_ITEMEXPANDEDA;
484         case TVN_BEGINDRAGW:      return TVN_BEGINDRAGA;
485         case TVN_BEGINRDRAGW:     return TVN_BEGINRDRAGA;
486         case TVN_DELETEITEMW:     return TVN_DELETEITEMA;
487         case TVN_BEGINLABELEDITW: return TVN_BEGINLABELEDITA;
488         case TVN_ENDLABELEDITW:   return TVN_ENDLABELEDITA;
489         case TVN_GETINFOTIPW:     return TVN_GETINFOTIPA;
490         }
491     }
492     return code;
493 }
494 
495 static LRESULT
496 TREEVIEW_SendRealNotify(const TREEVIEW_INFO *infoPtr, WPARAM wParam, LPARAM lParam)
497 {
498     TRACE("wParam=%ld, lParam=%ld\n", wParam, lParam);
499     return SendMessageW(infoPtr->hwndNotify, WM_NOTIFY, wParam, lParam);
500 }
501 
502 static BOOL
503 TREEVIEW_SendSimpleNotify(const TREEVIEW_INFO *infoPtr, UINT code)
504 {
505     NMHDR nmhdr;
506     HWND hwnd = infoPtr->hwnd;
507 
508     TRACE("%d\n", code);
509     nmhdr.hwndFrom = hwnd;
510     nmhdr.idFrom = GetWindowLongPtrW(hwnd, GWLP_ID);
511     nmhdr.code = get_notifycode(infoPtr, code);
512 
513     return (BOOL)TREEVIEW_SendRealNotify(infoPtr, nmhdr.idFrom, (LPARAM)&nmhdr);
514 }
515 
516 static VOID
517 TREEVIEW_TVItemFromItem(const TREEVIEW_INFO *infoPtr, UINT mask, TVITEMW *tvItem, TREEVIEW_ITEM *item)
518 {
519     tvItem->mask = mask;
520     tvItem->hItem = item;
521     tvItem->state = item->state;
522     tvItem->stateMask = 0;
523     tvItem->iImage = item->iImage;
524     tvItem->iSelectedImage = item->iSelectedImage;
525     tvItem->cChildren = item->cChildren;
526     tvItem->lParam = item->lParam;
527 
528     if(mask & TVIF_TEXT)
529     {
530         if (!infoPtr->bNtfUnicode)
531         {
532             tvItem->cchTextMax = WideCharToMultiByte( CP_ACP, 0, item->pszText, -1, NULL, 0, NULL, NULL );
533             tvItem->pszText = Alloc (tvItem->cchTextMax);
534             WideCharToMultiByte( CP_ACP, 0, item->pszText, -1, (LPSTR)tvItem->pszText, tvItem->cchTextMax, 0, 0 );
535         }
536         else
537         {
538             tvItem->cchTextMax = item->cchTextMax;
539             tvItem->pszText = item->pszText;
540         }
541     }
542     else
543     {
544         tvItem->cchTextMax = 0;
545         tvItem->pszText = NULL;
546     }
547 }
548 
549 static BOOL
550 TREEVIEW_SendTreeviewNotify(const TREEVIEW_INFO *infoPtr, UINT code, UINT action,
551                             UINT mask, HTREEITEM oldItem, HTREEITEM newItem)
552 {
553     HWND hwnd = infoPtr->hwnd;
554     NMTREEVIEWW nmhdr;
555     BOOL ret;
556 
557     TRACE("code:%d action:%x olditem:%p newitem:%p\n",
558           code, action, oldItem, newItem);
559 
560     ZeroMemory(&nmhdr, sizeof(NMTREEVIEWW));
561 
562     nmhdr.hdr.hwndFrom = hwnd;
563     nmhdr.hdr.idFrom = GetWindowLongPtrW(hwnd, GWLP_ID);
564     nmhdr.hdr.code = get_notifycode(infoPtr, code);
565     nmhdr.action = action;
566 
567     if (oldItem)
568         TREEVIEW_TVItemFromItem(infoPtr, mask, &nmhdr.itemOld, oldItem);
569 
570     if (newItem)
571         TREEVIEW_TVItemFromItem(infoPtr, mask, &nmhdr.itemNew, newItem);
572 
573     nmhdr.ptDrag.x = 0;
574     nmhdr.ptDrag.y = 0;
575 
576     ret = (BOOL)TREEVIEW_SendRealNotify(infoPtr, nmhdr.hdr.idFrom, (LPARAM)&nmhdr);
577     if (!infoPtr->bNtfUnicode)
578     {
579         Free(nmhdr.itemOld.pszText);
580         Free(nmhdr.itemNew.pszText);
581     }
582     return ret;
583 }
584 
585 static BOOL
586 TREEVIEW_SendTreeviewDnDNotify(const TREEVIEW_INFO *infoPtr, UINT code,
587                                HTREEITEM dragItem, POINT pt)
588 {
589     HWND hwnd = infoPtr->hwnd;
590     NMTREEVIEWW nmhdr;
591 
592     TRACE("code:%d dragitem:%p\n", code, dragItem);
593 
594     nmhdr.hdr.hwndFrom = hwnd;
595     nmhdr.hdr.idFrom = GetWindowLongPtrW(hwnd, GWLP_ID);
596     nmhdr.hdr.code = get_notifycode(infoPtr, code);
597     nmhdr.action = 0;
598     nmhdr.itemNew.mask = TVIF_STATE | TVIF_PARAM | TVIF_HANDLE;
599     nmhdr.itemNew.hItem = dragItem;
600     nmhdr.itemNew.state = dragItem->state;
601     nmhdr.itemNew.lParam = dragItem->lParam;
602 
603     nmhdr.ptDrag.x = pt.x;
604     nmhdr.ptDrag.y = pt.y;
605 
606     return (BOOL)TREEVIEW_SendRealNotify(infoPtr, nmhdr.hdr.idFrom, (LPARAM)&nmhdr);
607 }
608 
609 
610 static BOOL
611 TREEVIEW_SendCustomDrawNotify(const TREEVIEW_INFO *infoPtr, DWORD dwDrawStage,
612                               HDC hdc, RECT rc)
613 {
614     HWND hwnd = infoPtr->hwnd;
615     NMTVCUSTOMDRAW nmcdhdr;
616     LPNMCUSTOMDRAW nmcd;
617 
618     TRACE("drawstage:%x hdc:%p\n", dwDrawStage, hdc);
619 
620     nmcd = &nmcdhdr.nmcd;
621     nmcd->hdr.hwndFrom = hwnd;
622     nmcd->hdr.idFrom = GetWindowLongPtrW(hwnd, GWLP_ID);
623     nmcd->hdr.code = NM_CUSTOMDRAW;
624     nmcd->dwDrawStage = dwDrawStage;
625     nmcd->hdc = hdc;
626     nmcd->rc = rc;
627     nmcd->dwItemSpec = 0;
628     nmcd->uItemState = 0;
629     nmcd->lItemlParam = 0;
630     nmcdhdr.clrText = infoPtr->clrText;
631     nmcdhdr.clrTextBk = infoPtr->clrBk;
632     nmcdhdr.iLevel = 0;
633 
634     return (BOOL)TREEVIEW_SendRealNotify(infoPtr, nmcd->hdr.idFrom, (LPARAM)&nmcdhdr);
635 }
636 
637 
638 
639 /* FIXME: need to find out when the flags in uItemState need to be set */
640 
641 static BOOL
642 TREEVIEW_SendCustomDrawItemNotify(const TREEVIEW_INFO *infoPtr, HDC hdc,
643                                   TREEVIEW_ITEM *wineItem, UINT uItemDrawState,
644                                   NMTVCUSTOMDRAW *nmcdhdr)
645 {
646     HWND hwnd = infoPtr->hwnd;
647     LPNMCUSTOMDRAW nmcd;
648     DWORD dwDrawStage;
649     DWORD_PTR dwItemSpec;
650     UINT uItemState;
651     INT retval;
652 
653     dwDrawStage = CDDS_ITEM | uItemDrawState;
654     dwItemSpec = (DWORD_PTR)wineItem;
655     uItemState = 0;
656     if (wineItem->state & TVIS_SELECTED)
657         uItemState |= CDIS_SELECTED;
658     if (wineItem == infoPtr->selectedItem)
659         uItemState |= CDIS_FOCUS;
660     if (wineItem == infoPtr->hotItem)
661         uItemState |= CDIS_HOT;
662 
663     nmcd = &nmcdhdr->nmcd;
664     nmcd->hdr.hwndFrom = hwnd;
665     nmcd->hdr.idFrom = GetWindowLongPtrW(hwnd, GWLP_ID);
666     nmcd->hdr.code = NM_CUSTOMDRAW;
667     nmcd->dwDrawStage = dwDrawStage;
668     nmcd->hdc = hdc;
669     nmcd->rc = wineItem->rect;
670     nmcd->dwItemSpec = dwItemSpec;
671     nmcd->uItemState = uItemState;
672     nmcd->lItemlParam = wineItem->lParam;
673     nmcdhdr->iLevel = wineItem->iLevel;
674 
675     TRACE("drawstage:%x hdc:%p item:%lx, itemstate:%x, lItemlParam:%lx\n",
676           nmcd->dwDrawStage, nmcd->hdc, nmcd->dwItemSpec,
677           nmcd->uItemState, nmcd->lItemlParam);
678 
679     retval = TREEVIEW_SendRealNotify(infoPtr, nmcd->hdr.idFrom, (LPARAM)nmcdhdr);
680 
681     return retval;
682 }
683 
684 static BOOL
685 TREEVIEW_BeginLabelEditNotify(const TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *editItem)
686 {
687     HWND hwnd = infoPtr->hwnd;
688     NMTVDISPINFOW tvdi;
689     BOOL ret;
690 
691     tvdi.hdr.hwndFrom = hwnd;
692     tvdi.hdr.idFrom = GetWindowLongPtrW(hwnd, GWLP_ID);
693     tvdi.hdr.code = get_notifycode(infoPtr, TVN_BEGINLABELEDITW);
694 
695     TREEVIEW_TVItemFromItem(infoPtr, TVIF_HANDLE | TVIF_STATE | TVIF_PARAM | TVIF_TEXT,
696                             &tvdi.item, editItem);
697 
698     ret = (BOOL)TREEVIEW_SendRealNotify(infoPtr, tvdi.hdr.idFrom, (LPARAM)&tvdi);
699 
700     if (!infoPtr->bNtfUnicode)
701         Free(tvdi.item.pszText);
702 
703     return ret;
704 }
705 
706 static void
707 TREEVIEW_UpdateDispInfo(const TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *wineItem,
708                         UINT mask)
709 {
710     NMTVDISPINFOEXW callback;
711     HWND hwnd = infoPtr->hwnd;
712 
713     TRACE("mask %x callbackMask %x\n", mask, wineItem->callbackMask);
714     mask &= wineItem->callbackMask;
715 
716     if (mask == 0) return;
717 
718     callback.hdr.hwndFrom         = hwnd;
719     callback.hdr.idFrom           = GetWindowLongPtrW(hwnd, GWLP_ID);
720     callback.hdr.code             = get_notifycode(infoPtr, TVN_GETDISPINFOW);
721 
722     /* 'state' always contains valid value, as well as 'lParam'.
723      * All other parameters are uninitialized.
724      */
725     callback.item.pszText         = wineItem->pszText;
726     callback.item.cchTextMax      = wineItem->cchTextMax;
727     callback.item.mask            = mask;
728     callback.item.hItem           = wineItem;
729     callback.item.state           = wineItem->state;
730     callback.item.lParam          = wineItem->lParam;
731 
732     /* If text is changed we need to recalculate textWidth */
733     if (mask & TVIF_TEXT)
734        wineItem->textWidth = 0;
735 
736     TREEVIEW_SendRealNotify(infoPtr, callback.hdr.idFrom, (LPARAM)&callback);
737 
738     /* It may have changed due to a call to SetItem. */
739     mask &= wineItem->callbackMask;
740 
741     if ((mask & TVIF_TEXT) && callback.item.pszText != wineItem->pszText)
742     {
743         /* Instead of copying text into our buffer user specified its own */
744         if (!infoPtr->bNtfUnicode) {
745             LPWSTR newText;
746             int buflen;
747             int len = MultiByteToWideChar( CP_ACP, 0,
748                                            (LPSTR)callback.item.pszText, -1,
749                                            NULL, 0);
750             buflen = max((len)*sizeof(WCHAR), TEXT_CALLBACK_SIZE);
751             newText = ReAlloc(wineItem->pszText, buflen);
752 
753             TRACE("returned str %s, len=%d, buflen=%d\n",
754                   debugstr_a((LPSTR)callback.item.pszText), len, buflen);
755 
756             if (newText)
757             {
758                 wineItem->pszText = newText;
759                 MultiByteToWideChar( CP_ACP, 0,
760                                      (LPSTR)callback.item.pszText, -1,
761                                      wineItem->pszText, buflen/sizeof(WCHAR));
762                 wineItem->cchTextMax = buflen/sizeof(WCHAR);
763             }
764             /* If ReAlloc fails we have nothing to do, but keep original text */
765         }
766         else {
767             int len = max(lstrlenW(callback.item.pszText) + 1,
768                           TEXT_CALLBACK_SIZE);
769             LPWSTR newText = ReAlloc(wineItem->pszText, len);
770 
771             TRACE("returned wstr %s, len=%d\n",
772                   debugstr_w(callback.item.pszText), len);
773 
774             if (newText)
775             {
776                 wineItem->pszText = newText;
777                 strcpyW(wineItem->pszText, callback.item.pszText);
778                 wineItem->cchTextMax = len;
779             }
780             /* If ReAlloc fails we have nothing to do, but keep original text */
781         }
782     }
783     else if (mask & TVIF_TEXT) {
784         /* User put text into our buffer, that is ok unless A string */
785         if (!infoPtr->bNtfUnicode) {
786             LPWSTR newText;
787             LPWSTR oldText = NULL;
788             int buflen;
789             int len = MultiByteToWideChar( CP_ACP, 0,
790                                           (LPSTR)callback.item.pszText, -1,
791                                            NULL, 0);
792             buflen = max((len)*sizeof(WCHAR), TEXT_CALLBACK_SIZE);
793             newText = Alloc(buflen);
794 
795             TRACE("same buffer str %s, len=%d, buflen=%d\n",
796                   debugstr_a((LPSTR)callback.item.pszText), len, buflen);
797 
798             if (newText)
799             {
800                 oldText = wineItem->pszText;
801                 wineItem->pszText = newText;
802                 MultiByteToWideChar( CP_ACP, 0,
803                                      (LPSTR)callback.item.pszText, -1,
804                                      wineItem->pszText, buflen/sizeof(WCHAR));
805                 wineItem->cchTextMax = buflen/sizeof(WCHAR);
806                 Free(oldText);
807             }
808         }
809     }
810 
811     if (mask & TVIF_IMAGE)
812         wineItem->iImage = callback.item.iImage;
813 
814     if (mask & TVIF_SELECTEDIMAGE)
815         wineItem->iSelectedImage = callback.item.iSelectedImage;
816 
817     if (mask & TVIF_CHILDREN)
818         wineItem->cChildren = callback.item.cChildren;
819 
820     /* These members are now permanently set. */
821     if (callback.item.mask & TVIF_DI_SETITEM)
822         wineItem->callbackMask &= ~callback.item.mask;
823 }
824 
825 /***************************************************************************
826  * This function uses cChildren field to decide whether the item has
827  * children or not.
828  * Note: if this returns TRUE, the child items may not actually exist,
829  * they could be virtual.
830  *
831  * Just use wineItem->firstChild to check for physical children.
832  */
833 static BOOL
834 TREEVIEW_HasChildren(const TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *wineItem)
835 {
836     TREEVIEW_UpdateDispInfo(infoPtr, wineItem, TVIF_CHILDREN);
837 
838     return wineItem->cChildren > 0;
839 }
840 
841 static INT TREEVIEW_NotifyFormat (TREEVIEW_INFO *infoPtr, HWND hwndFrom, UINT nCommand)
842 {
843     INT format;
844 
845     TRACE("(hwndFrom=%p, nCommand=%d)\n", hwndFrom, nCommand);
846 
847     if (nCommand != NF_REQUERY) return 0;
848 
849     format = SendMessageW(hwndFrom, WM_NOTIFYFORMAT, (WPARAM)infoPtr->hwnd, NF_QUERY);
850     TRACE("format=%d\n", format);
851 
852     if (format != NFR_ANSI && format != NFR_UNICODE) return 0;
853 
854     infoPtr->bNtfUnicode = (format == NFR_UNICODE);
855 
856     return format;
857 }
858 
859 /* Item Position ********************************************************/
860 
861 /* Compute linesOffset, stateOffset, imageOffset, textOffset of an item. */
862 static VOID
863 TREEVIEW_ComputeItemInternalMetrics(const TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *item)
864 {
865     /* Same effect, different optimisation. */
866 #if 0
867     BOOL lar = ((infoPtr->dwStyle & TVS_LINESATROOT)
868                 && (infoPtr->dwStyle & (TVS_HASLINES|TVS_HASBUTTONS)));
869 #else
870     BOOL lar = ((infoPtr->dwStyle
871                  & (TVS_LINESATROOT|TVS_HASLINES|TVS_HASBUTTONS))
872                 > TVS_LINESATROOT);
873 #endif
874 
875     item->linesOffset = infoPtr->uIndent * (lar ? item->iLevel : item->iLevel - 1)
876         - infoPtr->scrollX;
877     item->stateOffset = item->linesOffset + infoPtr->uIndent;
878     item->imageOffset = item->stateOffset
879         + (STATEIMAGEINDEX(item->state) ? infoPtr->stateImageWidth : 0);
880     item->textOffset  = item->imageOffset + infoPtr->normalImageWidth;
881 }
882 
883 static VOID
884 TREEVIEW_ComputeTextWidth(const TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *item, HDC hDC)
885 {
886     HDC hdc;
887     HFONT hOldFont=0;
888     SIZE sz;
889 
890     /* DRAW's OM docker creates items like this */
891     if (item->pszText == NULL)
892     {
893         item->textWidth = 0;
894         return;
895     }
896 
897     if (hDC != 0)
898     {
899         hdc = hDC;
900     }
901     else
902     {
903         hdc = GetDC(infoPtr->hwnd);
904         hOldFont = SelectObject(hdc, TREEVIEW_FontForItem(infoPtr, item));
905     }
906 
907     GetTextExtentPoint32W(hdc, item->pszText, strlenW(item->pszText), &sz);
908     item->textWidth = sz.cx;
909 
910     if (hDC == 0)
911     {
912         SelectObject(hdc, hOldFont);
913         ReleaseDC(0, hdc);
914     }
915 }
916 
917 static VOID
918 TREEVIEW_ComputeItemRect(const TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *item)
919 {
920     item->rect.top = infoPtr->uItemHeight *
921         (item->visibleOrder - infoPtr->firstVisible->visibleOrder);
922 
923     item->rect.bottom = item->rect.top
924         + infoPtr->uItemHeight * item->iIntegral - 1;
925 
926     item->rect.left = 0;
927     item->rect.right = infoPtr->clientWidth;
928 }
929 
930 /* We know that only items after start need their order updated. */
931 static void
932 TREEVIEW_RecalculateVisibleOrder(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *start)
933 {
934     TREEVIEW_ITEM *item;
935     int order;
936 
937     if (!start)
938     {
939         start = infoPtr->root->firstChild;
940         order = 0;
941     }
942     else
943         order = start->visibleOrder;
944 
945     for (item = start; item != NULL;
946          item = TREEVIEW_GetNextListItem(infoPtr, item))
947     {
948         if (!ISVISIBLE(item) && order > 0)
949                 TREEVIEW_ComputeItemInternalMetrics(infoPtr, item);
950         item->visibleOrder = order;
951         order += item->iIntegral;
952     }
953 
954     infoPtr->maxVisibleOrder = order;
955 
956     for (item = start; item != NULL;
957          item = TREEVIEW_GetNextListItem(infoPtr, item))
958     {
959         TREEVIEW_ComputeItemRect(infoPtr, item);
960     }
961 }
962 
963 
964 /* Update metrics of all items in selected subtree.
965  * root must be expanded
966  */
967 static VOID
968 TREEVIEW_UpdateSubTree(const TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *root)
969 {
970    TREEVIEW_ITEM *sibling;
971    HDC hdc;
972    HFONT hOldFont;
973 
974    if (!root->firstChild || !(root->state & TVIS_EXPANDED))
975       return;
976 
977    root->state &= ~TVIS_EXPANDED;
978    sibling = TREEVIEW_GetNextListItem(infoPtr, root);
979    root->state |= TVIS_EXPANDED;
980 
981    hdc = GetDC(infoPtr->hwnd);
982    hOldFont = SelectObject(hdc, infoPtr->hFont);
983 
984    for (; root != sibling;
985         root = TREEVIEW_GetNextListItem(infoPtr, root))
986    {
987       TREEVIEW_ComputeItemInternalMetrics(infoPtr, root);
988 
989       if (root->callbackMask & TVIF_TEXT)
990          TREEVIEW_UpdateDispInfo(infoPtr, root, TVIF_TEXT);
991 
992       if (root->textWidth == 0)
993       {
994          SelectObject(hdc, TREEVIEW_FontForItem(infoPtr, root));
995          TREEVIEW_ComputeTextWidth(infoPtr, root, hdc);
996       }
997    }
998 
999    SelectObject(hdc, hOldFont);
1000    ReleaseDC(infoPtr->hwnd, hdc);
1001 }
1002 
1003 /* Item Allocation **********************************************************/
1004 
1005 static TREEVIEW_ITEM *
1006 TREEVIEW_AllocateItem(const TREEVIEW_INFO *infoPtr)
1007 {
1008     TREEVIEW_ITEM *newItem = Alloc(sizeof(TREEVIEW_ITEM));
1009 
1010     if (!newItem)
1011         return NULL;
1012 
1013     /* I_IMAGENONE would make more sense but this is neither what is
1014      * documented (MSDN doesn't specify) nor what Windows actually does
1015      * (it sets it to zero)... and I can so imagine an application using
1016      * inc/dec to toggle the images. */
1017     newItem->iImage = 0;
1018     newItem->iSelectedImage = 0;
1019 
1020     if (DPA_InsertPtr(infoPtr->items, INT_MAX, newItem) == -1)
1021     {
1022         Free(newItem);
1023         return NULL;
1024     }
1025 
1026     return newItem;
1027 }
1028 
1029 /* Exact opposite of TREEVIEW_AllocateItem. In particular, it does not
1030  * free item->pszText. */
1031 static void
1032 TREEVIEW_FreeItem(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *item)
1033 {
1034     DPA_DeletePtr(infoPtr->items, DPA_GetPtrIndex(infoPtr->items, item));
1035     if (infoPtr->selectedItem == item)
1036         infoPtr->selectedItem = NULL;
1037     if (infoPtr->hotItem == item)
1038         infoPtr->hotItem = NULL;
1039     if (infoPtr->focusedItem == item)
1040         infoPtr->focusedItem = NULL;
1041     if (infoPtr->firstVisible == item)
1042         infoPtr->firstVisible = NULL;
1043     if (infoPtr->dropItem == item)
1044         infoPtr->dropItem = NULL;
1045     if (infoPtr->insertMarkItem == item)
1046         infoPtr->insertMarkItem = NULL;
1047     Free(item);
1048 }
1049 
1050 
1051 /* Item Insertion *******************************************************/
1052 
1053 /***************************************************************************
1054  * This method inserts newItem before sibling as a child of parent.
1055  * sibling can be NULL, but only if parent has no children.
1056  */
1057 static void
1058 TREEVIEW_InsertBefore(TREEVIEW_ITEM *newItem, TREEVIEW_ITEM *sibling,
1059                       TREEVIEW_ITEM *parent)
1060 {
1061     assert(parent != NULL);
1062 
1063     if (sibling != NULL)
1064     {
1065         assert(sibling->parent == parent);
1066 
1067         if (sibling->prevSibling != NULL)
1068             sibling->prevSibling->nextSibling = newItem;
1069 
1070         newItem->prevSibling = sibling->prevSibling;
1071         sibling->prevSibling = newItem;
1072     }
1073     else
1074        newItem->prevSibling = NULL;
1075 
1076     newItem->nextSibling = sibling;
1077 
1078     if (parent->firstChild == sibling)
1079         parent->firstChild = newItem;
1080 
1081     if (parent->lastChild == NULL)
1082         parent->lastChild = newItem;
1083 }
1084 
1085 /***************************************************************************
1086  * This method inserts newItem after sibling as a child of parent.
1087  * sibling can be NULL, but only if parent has no children.
1088  */
1089 static void
1090 TREEVIEW_InsertAfter(TREEVIEW_ITEM *newItem, TREEVIEW_ITEM *sibling,
1091                      TREEVIEW_ITEM *parent)
1092 {
1093     assert(parent != NULL);
1094 
1095     if (sibling != NULL)
1096     {
1097         assert(sibling->parent == parent);
1098 
1099         if (sibling->nextSibling != NULL)
1100             sibling->nextSibling->prevSibling = newItem;
1101 
1102         newItem->nextSibling = sibling->nextSibling;
1103         sibling->nextSibling = newItem;
1104     }
1105     else
1106        newItem->nextSibling = NULL;
1107 
1108     newItem->prevSibling = sibling;
1109 
1110     if (parent->lastChild == sibling)
1111         parent->lastChild = newItem;
1112 
1113     if (parent->firstChild == NULL)
1114         parent->firstChild = newItem;
1115 }
1116 
1117 static BOOL
1118 TREEVIEW_DoSetItemT(const TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *wineItem,
1119                    const TVITEMEXW *tvItem, BOOL isW)
1120 {
1121     UINT callbackClear = 0;
1122     UINT callbackSet = 0;
1123 
1124     TRACE("item %p\n", wineItem);
1125     /* Do this first in case it fails. */
1126     if (tvItem->mask & TVIF_TEXT)
1127     {
1128         wineItem->textWidth = 0; /* force width recalculation */
1129         if (tvItem->pszText != LPSTR_TEXTCALLBACKW && tvItem->pszText != NULL) /* covers != TEXTCALLBACKA too, and undocumented: pszText of NULL also means TEXTCALLBACK */
1130         {
1131             int len;
1132             LPWSTR newText;
1133             if (isW)
1134                 len = lstrlenW(tvItem->pszText) + 1;
1135             else
1136                 len = MultiByteToWideChar(CP_ACP, 0, (LPSTR)tvItem->pszText, -1, NULL, 0);
1137 
1138             newText  = ReAlloc(wineItem->pszText, len * sizeof(WCHAR));
1139 
1140             if (newText == NULL) return FALSE;
1141 
1142             callbackClear |= TVIF_TEXT;
1143 
1144             wineItem->pszText = newText;
1145             wineItem->cchTextMax = len;
1146             if (isW)
1147                 lstrcpynW(wineItem->pszText, tvItem->pszText, len);
1148             else
1149                 MultiByteToWideChar(CP_ACP, 0, (LPSTR)tvItem->pszText, -1,
1150                                     wineItem->pszText, len);
1151 
1152             TRACE("setting text %s, item %p\n", debugstr_w(wineItem->pszText), wineItem);
1153         }
1154         else
1155         {
1156             callbackSet |= TVIF_TEXT;
1157 
1158             wineItem->pszText = ReAlloc(wineItem->pszText,
1159                                         TEXT_CALLBACK_SIZE * sizeof(WCHAR));
1160             wineItem->cchTextMax = TEXT_CALLBACK_SIZE;
1161             TRACE("setting callback, item %p\n", wineItem);
1162         }
1163     }
1164 
1165     if (tvItem->mask & TVIF_CHILDREN)
1166     {
1167         wineItem->cChildren = tvItem->cChildren;
1168 
1169         if (wineItem->cChildren == I_CHILDRENCALLBACK)
1170             callbackSet |= TVIF_CHILDREN;
1171         else
1172             callbackClear |= TVIF_CHILDREN;
1173     }
1174 
1175     if (tvItem->mask & TVIF_IMAGE)
1176     {
1177         wineItem->iImage = tvItem->iImage;
1178 
1179         if (wineItem->iImage == I_IMAGECALLBACK)
1180             callbackSet |= TVIF_IMAGE;
1181         else
1182             callbackClear |= TVIF_IMAGE;
1183     }
1184 
1185     if (tvItem->mask & TVIF_SELECTEDIMAGE)
1186     {
1187         wineItem->iSelectedImage = tvItem->iSelectedImage;
1188 
1189         if (wineItem->iSelectedImage == I_IMAGECALLBACK)
1190             callbackSet |= TVIF_SELECTEDIMAGE;
1191         else
1192             callbackClear |= TVIF_SELECTEDIMAGE;
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     wineItem->callbackMask |= callbackSet;
1212     wineItem->callbackMask &= ~callbackClear;
1213 
1214     return TRUE;
1215 }
1216 
1217 /* Note that the new item is pre-zeroed. */
1218 static LRESULT
1219 TREEVIEW_InsertItemT(TREEVIEW_INFO *infoPtr, const TVINSERTSTRUCTW *ptdi, BOOL isW)
1220 {
1221     const TVITEMEXW *tvItem = &ptdi->u.itemex;
1222     HTREEITEM insertAfter;
1223     TREEVIEW_ITEM *newItem, *parentItem;
1224     BOOL bTextUpdated = FALSE;
1225 
1226     if (ptdi->hParent == TVI_ROOT || ptdi->hParent == 0)
1227     {
1228         parentItem = infoPtr->root;
1229     }
1230     else
1231     {
1232         parentItem = ptdi->hParent;
1233 
1234         if (!TREEVIEW_ValidItem(infoPtr, parentItem))
1235         {
1236             WARN("invalid parent %p\n", parentItem);
1237             return 0;
1238         }
1239     }
1240 
1241     insertAfter = ptdi->hInsertAfter;
1242 
1243     /* Validate this now for convenience. */
1244     switch ((DWORD_PTR)insertAfter)
1245     {
1246     case (DWORD_PTR)TVI_FIRST:
1247     case (DWORD_PTR)TVI_LAST:
1248     case (DWORD_PTR)TVI_SORT:
1249         break;
1250 
1251     default:
1252         if (!TREEVIEW_ValidItem(infoPtr, insertAfter) ||
1253             insertAfter->parent != parentItem)
1254         {
1255             WARN("invalid insert after %p\n", insertAfter);
1256             insertAfter = TVI_LAST;
1257         }
1258     }
1259 
1260     TRACE("parent %p position %p: %s\n", parentItem, insertAfter,
1261           (tvItem->mask & TVIF_TEXT)
1262           ? ((tvItem->pszText == LPSTR_TEXTCALLBACKW) ? "<callback>"
1263              : (isW ? debugstr_w(tvItem->pszText) : debugstr_a((LPSTR)tvItem->pszText)))
1264           : "<no label>");
1265 
1266     newItem = TREEVIEW_AllocateItem(infoPtr);
1267     if (newItem == NULL)
1268         return 0;
1269 
1270     newItem->parent = parentItem;
1271     newItem->iIntegral = 1;
1272     newItem->visibleOrder = -1;
1273 
1274     if (!TREEVIEW_DoSetItemT(infoPtr, newItem, tvItem, isW))
1275         return 0;
1276 
1277     /* After this point, nothing can fail. (Except for TVI_SORT.) */
1278 
1279     infoPtr->uNumItems++;
1280 
1281     switch ((DWORD_PTR)insertAfter)
1282     {
1283     case (DWORD_PTR)TVI_FIRST:
1284         {
1285            TREEVIEW_ITEM *originalFirst = parentItem->firstChild;
1286            TREEVIEW_InsertBefore(newItem, parentItem->firstChild, parentItem);
1287            if (infoPtr->firstVisible == originalFirst)
1288               TREEVIEW_SetFirstVisible(infoPtr, newItem, TRUE);
1289         }
1290         break;
1291 
1292     case (DWORD_PTR)TVI_LAST:
1293         TREEVIEW_InsertAfter(newItem, parentItem->lastChild, parentItem);
1294         break;
1295 
1296         /* hInsertAfter names a specific item we want to insert after */
1297     default:
1298         TREEVIEW_InsertAfter(newItem, insertAfter, insertAfter->parent);
1299         break;
1300 
1301     case (DWORD_PTR)TVI_SORT:
1302         {
1303             TREEVIEW_ITEM *aChild;
1304             TREEVIEW_ITEM *previousChild = NULL;
1305             TREEVIEW_ITEM *originalFirst = parentItem->firstChild;
1306             BOOL bItemInserted = FALSE;
1307 
1308             aChild = parentItem->firstChild;
1309 
1310             bTextUpdated = TRUE;
1311             TREEVIEW_UpdateDispInfo(infoPtr, newItem, TVIF_TEXT);
1312 
1313             /* Iterate the parent children to see where we fit in */
1314             while (aChild != NULL)
1315             {
1316                 INT comp;
1317 
1318                 TREEVIEW_UpdateDispInfo(infoPtr, aChild, TVIF_TEXT);
1319                 comp = lstrcmpW(newItem->pszText, aChild->pszText);
1320 
1321                 if (comp < 0)   /* we are smaller than the current one */
1322                 {
1323                     TREEVIEW_InsertBefore(newItem, aChild, parentItem);
1324                     if (infoPtr->firstVisible == originalFirst &&
1325                         aChild == originalFirst)
1326                         TREEVIEW_SetFirstVisible(infoPtr, newItem, TRUE);
1327                     bItemInserted = TRUE;
1328                     break;
1329                 }
1330                 else if (comp > 0)      /* we are bigger than the current one */
1331                 {
1332                     previousChild = aChild;
1333 
1334                     /* This will help us to exit if there is no more sibling */
1335                     aChild = (aChild->nextSibling == 0)
1336                         ? NULL
1337                         : aChild->nextSibling;
1338 
1339                     /* Look at the next item */
1340                     continue;
1341                 }
1342                 else if (comp == 0)
1343                 {
1344                     /*
1345                      * An item with this name is already existing, therefore,
1346                      * we add after the one we found
1347                      */
1348                     TREEVIEW_InsertAfter(newItem, aChild, parentItem);
1349                     bItemInserted = TRUE;
1350                     break;
1351                 }
1352             }
1353 
1354             /*
1355              * we reach the end of the child list and the item has not
1356              * yet been inserted, therefore, insert it after the last child.
1357              */
1358             if ((!bItemInserted) && (aChild == NULL))
1359                 TREEVIEW_InsertAfter(newItem, previousChild, parentItem);
1360 
1361             break;
1362         }
1363     }
1364 
1365 
1366     TRACE("new item %p; parent %p, mask %x\n", newItem,
1367           newItem->parent, tvItem->mask);
1368 
1369     newItem->iLevel = newItem->parent->iLevel + 1;
1370 
1371     if (newItem->parent->cChildren == 0)
1372         newItem->parent->cChildren = 1;
1373 
1374     if (infoPtr->dwStyle & TVS_CHECKBOXES)
1375     {
1376         if (STATEIMAGEINDEX(newItem->state) == 0)
1377             newItem->state |= INDEXTOSTATEIMAGEMASK(1);
1378     }
1379 
1380     if (infoPtr->firstVisible == NULL)
1381         infoPtr->firstVisible = newItem;
1382 
1383     TREEVIEW_VerifyTree(infoPtr);
1384 
1385     if (!infoPtr->bRedraw) return (LRESULT)newItem;
1386 
1387     if (parentItem == infoPtr->root ||
1388         (ISVISIBLE(parentItem) && parentItem->state & TVIS_EXPANDED))
1389     {
1390        TREEVIEW_ITEM *item;
1391        TREEVIEW_ITEM *prev = TREEVIEW_GetPrevListItem(infoPtr, newItem);
1392 
1393        TREEVIEW_RecalculateVisibleOrder(infoPtr, prev);
1394        TREEVIEW_ComputeItemInternalMetrics(infoPtr, newItem);
1395 
1396        if (!bTextUpdated)
1397           TREEVIEW_UpdateDispInfo(infoPtr, newItem, TVIF_TEXT);
1398 
1399        TREEVIEW_ComputeTextWidth(infoPtr, newItem, 0);
1400        TREEVIEW_UpdateScrollBars(infoPtr);
1401     /*
1402      * if the item was inserted in a visible part of the tree,
1403      * invalidate it, as well as those after it
1404      */
1405        for (item = newItem;
1406             item != NULL;
1407             item = TREEVIEW_GetNextListItem(infoPtr, item))
1408           TREEVIEW_Invalidate(infoPtr, item);
1409     }
1410     else
1411     {
1412        /* refresh treeview if newItem is the first item inserted under parentItem */
1413        if (ISVISIBLE(parentItem) && newItem->prevSibling == newItem->nextSibling)
1414        {
1415           /* parent got '+' - update it */
1416           TREEVIEW_Invalidate(infoPtr, parentItem);
1417        }
1418     }
1419 
1420     return (LRESULT)newItem;
1421 }
1422 
1423 /* Item Deletion ************************************************************/
1424 static void
1425 TREEVIEW_RemoveItem(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *wineItem);
1426 
1427 static void
1428 TREEVIEW_RemoveAllChildren(TREEVIEW_INFO *infoPtr, const TREEVIEW_ITEM *parentItem)
1429 {
1430     TREEVIEW_ITEM *kill = parentItem->firstChild;
1431 
1432     while (kill != NULL)
1433     {
1434         TREEVIEW_ITEM *next = kill->nextSibling;
1435 
1436         TREEVIEW_RemoveItem(infoPtr, kill);
1437 
1438         kill = next;
1439     }
1440 
1441     assert(parentItem->cChildren <= 0); /* I_CHILDRENCALLBACK or 0 */
1442     assert(parentItem->firstChild == NULL);
1443     assert(parentItem->lastChild == NULL);
1444 }
1445 
1446 static void
1447 TREEVIEW_UnlinkItem(const TREEVIEW_ITEM *item)
1448 {
1449     TREEVIEW_ITEM *parentItem = item->parent;
1450 
1451     assert(item != NULL);
1452     assert(item->parent != NULL); /* i.e. it must not be the root */
1453 
1454     if (parentItem->firstChild == item)
1455         parentItem->firstChild = item->nextSibling;
1456 
1457     if (parentItem->lastChild == item)
1458         parentItem->lastChild = item->prevSibling;
1459 
1460     if (parentItem->firstChild == NULL && parentItem->lastChild == NULL
1461         && parentItem->cChildren > 0)
1462         parentItem->cChildren = 0;
1463 
1464     if (item->prevSibling)
1465         item->prevSibling->nextSibling = item->nextSibling;
1466 
1467     if (item->nextSibling)
1468         item->nextSibling->prevSibling = item->prevSibling;
1469 }
1470 
1471 static void
1472 TREEVIEW_RemoveItem(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *wineItem)
1473 {
1474     TRACE("%p, (%s)\n", wineItem, TREEVIEW_ItemName(wineItem));
1475 
1476     TREEVIEW_SendTreeviewNotify(infoPtr, TVN_DELETEITEMW, TVC_UNKNOWN,
1477                                 TVIF_HANDLE | TVIF_PARAM, wineItem, 0);
1478 
1479     if (wineItem->firstChild)
1480         TREEVIEW_RemoveAllChildren(infoPtr, wineItem);
1481 
1482     TREEVIEW_UnlinkItem(wineItem);
1483 
1484     infoPtr->uNumItems--;
1485 
1486     if (wineItem->pszText != LPSTR_TEXTCALLBACKW)
1487         Free(wineItem->pszText);
1488 
1489     TREEVIEW_FreeItem(infoPtr, wineItem);
1490 }
1491 
1492 
1493 /* Empty out the tree. */
1494 static void
1495 TREEVIEW_RemoveTree(TREEVIEW_INFO *infoPtr)
1496 {
1497     TREEVIEW_RemoveAllChildren(infoPtr, infoPtr->root);
1498 
1499     assert(infoPtr->uNumItems == 0);    /* root isn't counted in uNumItems */
1500 }
1501 
1502 static LRESULT
1503 TREEVIEW_DeleteItem(TREEVIEW_INFO *infoPtr, HTREEITEM wineItem)
1504 {
1505     TREEVIEW_ITEM *newSelection = NULL;
1506     TREEVIEW_ITEM *newFirstVisible = NULL;
1507     TREEVIEW_ITEM *parent, *prev = NULL;
1508     BOOL visible = FALSE;
1509 
1510     if (wineItem == TVI_ROOT)
1511     {
1512         TRACE("TVI_ROOT\n");
1513         parent = infoPtr->root;
1514         newSelection = NULL;
1515         visible = TRUE;
1516         TREEVIEW_RemoveTree(infoPtr);
1517     }
1518     else
1519     {
1520         if (!TREEVIEW_ValidItem(infoPtr, wineItem))
1521             return FALSE;
1522 
1523         TRACE("%p (%s)\n", wineItem, TREEVIEW_ItemName(wineItem));
1524         parent = wineItem->parent;
1525 
1526         if (ISVISIBLE(wineItem))
1527         {
1528             prev = TREEVIEW_GetPrevListItem(infoPtr, wineItem);
1529             visible = TRUE;
1530         }
1531 
1532         if (infoPtr->selectedItem != NULL
1533             && (wineItem == infoPtr->selectedItem
1534                 || TREEVIEW_IsChildOf(wineItem, infoPtr->selectedItem)))
1535         {
1536             if (wineItem->nextSibling)
1537                 newSelection = wineItem->nextSibling;
1538             else if (wineItem->parent != infoPtr->root)
1539                 newSelection = wineItem->parent;
1540             else
1541                 newSelection = wineItem->prevSibling;
1542             TRACE("newSelection = %p\n", newSelection);
1543         }
1544 
1545         if (infoPtr->firstVisible == wineItem)
1546         {
1547             if (wineItem->nextSibling)
1548                newFirstVisible = wineItem->nextSibling;
1549             else if (wineItem->prevSibling)
1550                newFirstVisible = wineItem->prevSibling;
1551             else if (wineItem->parent != infoPtr->root)
1552                newFirstVisible = wineItem->parent;
1553                TREEVIEW_SetFirstVisible(infoPtr, NULL, TRUE);
1554         }
1555         else
1556             newFirstVisible = infoPtr->firstVisible;
1557 
1558         TREEVIEW_RemoveItem(infoPtr, wineItem);
1559     }
1560 
1561     /* Don't change if somebody else already has (infoPtr->selectedItem is cleared by FreeItem). */
1562     if (!infoPtr->selectedItem && newSelection)
1563     {
1564         if (TREEVIEW_ValidItem(infoPtr, newSelection))
1565             TREEVIEW_DoSelectItem(infoPtr, TVGN_CARET, newSelection, TVC_UNKNOWN);
1566     }
1567 
1568     /* Validate insertMark dropItem.
1569      * hotItem ??? - used for comparison only.
1570      */
1571     if (!TREEVIEW_ValidItem(infoPtr, infoPtr->insertMarkItem))
1572         infoPtr->insertMarkItem = 0;
1573 
1574     if (!TREEVIEW_ValidItem(infoPtr, infoPtr->dropItem))
1575         infoPtr->dropItem = 0;
1576 
1577     if (!TREEVIEW_ValidItem(infoPtr, newFirstVisible))
1578         newFirstVisible = infoPtr->root->firstChild;
1579 
1580     TREEVIEW_VerifyTree(infoPtr);
1581 
1582     if (!infoPtr->bRedraw) return TRUE;
1583 
1584     if (visible)
1585     {
1586        TREEVIEW_SetFirstVisible(infoPtr, newFirstVisible, TRUE);
1587        TREEVIEW_RecalculateVisibleOrder(infoPtr, prev);
1588        TREEVIEW_UpdateScrollBars(infoPtr);
1589        TREEVIEW_Invalidate(infoPtr, NULL);
1590     }
1591     else if (ISVISIBLE(parent) && !TREEVIEW_HasChildren(infoPtr, parent))
1592     {
1593        /* parent lost '+/-' - update it */
1594        TREEVIEW_Invalidate(infoPtr, parent);
1595     }
1596 
1597     return TRUE;
1598 }
1599 
1600 
1601 /* Get/Set Messages *********************************************************/
1602 static LRESULT
1603 TREEVIEW_SetRedraw(TREEVIEW_INFO* infoPtr, WPARAM wParam)
1604 {
1605     infoPtr->bRedraw = wParam ? TRUE : FALSE;
1606 
1607     if (infoPtr->bRedraw)
1608     {
1609         TREEVIEW_UpdateSubTree(infoPtr, infoPtr->root);
1610         TREEVIEW_RecalculateVisibleOrder(infoPtr, NULL);
1611         TREEVIEW_UpdateScrollBars(infoPtr);
1612         TREEVIEW_Invalidate(infoPtr, NULL);
1613     }
1614     return 0;
1615 }
1616 
1617 static LRESULT
1618 TREEVIEW_GetIndent(const TREEVIEW_INFO *infoPtr)
1619 {
1620     TRACE("\n");
1621     return infoPtr->uIndent;
1622 }
1623 
1624 static LRESULT
1625 TREEVIEW_SetIndent(TREEVIEW_INFO *infoPtr, UINT newIndent)
1626 {
1627     TRACE("\n");
1628 
1629     if (newIndent < MINIMUM_INDENT)
1630         newIndent = MINIMUM_INDENT;
1631 
1632     if (infoPtr->uIndent != newIndent)
1633     {
1634         infoPtr->uIndent = newIndent;
1635         TREEVIEW_UpdateSubTree(infoPtr, infoPtr->root);
1636         TREEVIEW_UpdateScrollBars(infoPtr);
1637         TREEVIEW_Invalidate(infoPtr, NULL);
1638     }
1639 
1640     return 0;
1641 }
1642 
1643 
1644 static LRESULT
1645 TREEVIEW_GetToolTips(const TREEVIEW_INFO *infoPtr)
1646 {
1647     TRACE("\n");
1648     return (LRESULT)infoPtr->hwndToolTip;
1649 }
1650 
1651 static LRESULT
1652 TREEVIEW_SetToolTips(TREEVIEW_INFO *infoPtr, HWND hwndTT)
1653 {
1654     HWND prevToolTip;
1655 
1656     TRACE("\n");
1657     prevToolTip = infoPtr->hwndToolTip;
1658     infoPtr->hwndToolTip = hwndTT;
1659 
1660     return (LRESULT)prevToolTip;
1661 }
1662 
1663 static LRESULT
1664 TREEVIEW_SetUnicodeFormat(TREEVIEW_INFO *infoPtr, BOOL fUnicode)
1665 {
1666     BOOL rc = infoPtr->bNtfUnicode;
1667     infoPtr->bNtfUnicode = fUnicode;
1668     return rc;
1669 }
1670 
1671 static LRESULT
1672 TREEVIEW_GetUnicodeFormat(const TREEVIEW_INFO *infoPtr)
1673 {
1674      return infoPtr->bNtfUnicode;
1675 }
1676 
1677 static LRESULT
1678 TREEVIEW_GetScrollTime(const TREEVIEW_INFO *infoPtr)
1679 {
1680     return infoPtr->uScrollTime;
1681 }
1682 
1683 static LRESULT
1684 TREEVIEW_SetScrollTime(TREEVIEW_INFO *infoPtr, UINT uScrollTime)
1685 {
1686     UINT uOldScrollTime = infoPtr->uScrollTime;
1687 
1688     infoPtr->uScrollTime = min(uScrollTime, 100);
1689 
1690     return uOldScrollTime;
1691 }
1692 
1693 
1694 static LRESULT
1695 TREEVIEW_GetImageList(const TREEVIEW_INFO *infoPtr, WPARAM wParam)
1696 {
1697     TRACE("\n");
1698 
1699     switch (wParam)
1700     {
1701     case TVSIL_NORMAL:
1702         return (LRESULT)infoPtr->himlNormal;
1703 
1704     case TVSIL_STATE:
1705         return (LRESULT)infoPtr->himlState;
1706 
1707     default:
1708         return 0;
1709     }
1710 }
1711 
1712 #define TVHEIGHT_MIN         16
1713 #define TVHEIGHT_FONT_ADJUST 3 /* 2 for focus border + 1 for margin some apps assume */
1714 
1715 /* Compute the natural height for items. */
1716 static UINT
1717 TREEVIEW_NaturalHeight(const TREEVIEW_INFO *infoPtr)
1718 {
1719     TEXTMETRICW tm;
1720     HDC hdc = GetDC(0);
1721     HFONT hOldFont = SelectObject(hdc, infoPtr->hFont);
1722     UINT height;
1723 
1724     /* Height is the maximum of:
1725      * 16 (a hack because our fonts are tiny), and
1726      * The text height + border & margin, and
1727      * The size of the normal image list
1728      */
1729     GetTextMetricsW(hdc, &tm);
1730     SelectObject(hdc, hOldFont);
1731     ReleaseDC(0, hdc);
1732 
1733     height = TVHEIGHT_MIN;
1734     if (height < tm.tmHeight + tm.tmExternalLeading + TVHEIGHT_FONT_ADJUST)
1735         height = tm.tmHeight + tm.tmExternalLeading + TVHEIGHT_FONT_ADJUST;
1736     if (height < infoPtr->normalImageHeight)
1737         height = infoPtr->normalImageHeight;
1738 
1739     /* Round down, unless we support odd ("non even") heights. */
1740     if (!(infoPtr->dwStyle & TVS_NONEVENHEIGHT))
1741         height &= ~1;
1742 
1743     return height;
1744 }
1745 
1746 static LRESULT
1747 TREEVIEW_SetImageList(TREEVIEW_INFO *infoPtr, WPARAM wParam, HIMAGELIST himlNew)
1748 {
1749     HIMAGELIST himlOld = 0;
1750     int oldWidth  = infoPtr->normalImageWidth;
1751     int oldHeight = infoPtr->normalImageHeight;
1752 
1753 
1754     TRACE("%lx,%p\n", wParam, himlNew);
1755 
1756     switch (wParam)
1757     {
1758     case TVSIL_NORMAL:
1759         himlOld = infoPtr->himlNormal;
1760         infoPtr->himlNormal = himlNew;
1761 
1762         if (himlNew != NULL)
1763             ImageList_GetIconSize(himlNew, &infoPtr->normalImageWidth,
1764                                   &infoPtr->normalImageHeight);
1765         else
1766         {
1767             infoPtr->normalImageWidth = 0;
1768             infoPtr->normalImageHeight = 0;
1769         }
1770 
1771         break;
1772 
1773     case TVSIL_STATE:
1774         himlOld = infoPtr->himlState;
1775         infoPtr->himlState = himlNew;
1776 
1777         if (himlNew != NULL)
1778             ImageList_GetIconSize(himlNew, &infoPtr->stateImageWidth,
1779                                   &infoPtr->stateImageHeight);
1780         else
1781         {
1782             infoPtr->stateImageWidth = 0;
1783             infoPtr->stateImageHeight = 0;
1784         }
1785 
1786         break;
1787     }
1788 
1789     if (oldWidth != infoPtr->normalImageWidth ||
1790         oldHeight != infoPtr->normalImageHeight)
1791     {
1792         BOOL bRecalcVisible = FALSE;
1793 
1794         if (oldHeight != infoPtr->normalImageHeight &&
1795             !infoPtr->bHeightSet)
1796         {
1797             infoPtr->uItemHeight = TREEVIEW_NaturalHeight(infoPtr);
1798             bRecalcVisible = TRUE;
1799         }
1800 
1801         if (infoPtr->normalImageWidth > MINIMUM_INDENT &&
1802             infoPtr->normalImageWidth != infoPtr->uIndent)
1803         {
1804             infoPtr->uIndent = infoPtr->normalImageWidth;
1805             bRecalcVisible = TRUE;
1806         }
1807 
1808         if (bRecalcVisible)
1809             TREEVIEW_RecalculateVisibleOrder(infoPtr, NULL);
1810 
1811        TREEVIEW_UpdateSubTree(infoPtr, infoPtr->root);
1812        TREEVIEW_UpdateScrollBars(infoPtr);
1813     }
1814 
1815     TREEVIEW_Invalidate(infoPtr, NULL);
1816 
1817     return (LRESULT)himlOld;
1818 }
1819 
1820 static LRESULT
1821 TREEVIEW_SetItemHeight(TREEVIEW_INFO *infoPtr, INT newHeight)
1822 {
1823     INT prevHeight = infoPtr->uItemHeight;
1824 
1825     TRACE("%d\n", newHeight);
1826     if (newHeight == -1)
1827     {
1828         infoPtr->uItemHeight = TREEVIEW_NaturalHeight(infoPtr);
1829         infoPtr->bHeightSet = FALSE;
1830     }
1831     else
1832     {
1833         infoPtr->uItemHeight = newHeight;
1834         infoPtr->bHeightSet = TRUE;
1835     }
1836 
1837     /* Round down, unless we support odd ("non even") heights. */
1838     if (!(infoPtr->dwStyle & TVS_NONEVENHEIGHT))
1839         infoPtr->uItemHeight &= ~1;
1840 
1841     if (infoPtr->uItemHeight != prevHeight)
1842     {
1843         TREEVIEW_RecalculateVisibleOrder(infoPtr, NULL);
1844         TREEVIEW_UpdateScrollBars(infoPtr);
1845         TREEVIEW_Invalidate(infoPtr, NULL);
1846     }
1847 
1848     return prevHeight;
1849 }
1850 
1851 static LRESULT
1852 TREEVIEW_GetItemHeight(const TREEVIEW_INFO *infoPtr)
1853 {
1854     TRACE("\n");
1855     return infoPtr->uItemHeight;
1856 }
1857 
1858 
1859 static LRESULT
1860 TREEVIEW_GetFont(const TREEVIEW_INFO *infoPtr)
1861 {
1862     TRACE("%p\n", infoPtr->hFont);
1863     return (LRESULT)infoPtr->hFont;
1864 }
1865 
1866 
1867 static INT CALLBACK
1868 TREEVIEW_ResetTextWidth(LPVOID pItem, LPVOID unused)
1869 {
1870     (void)unused;
1871 
1872     ((TREEVIEW_ITEM *)pItem)->textWidth = 0;
1873 
1874     return 1;
1875 }
1876 
1877 static LRESULT
1878 TREEVIEW_SetFont(TREEVIEW_INFO *infoPtr, HFONT hFont, BOOL bRedraw)
1879 {
1880     UINT uHeight = infoPtr->uItemHeight;
1881 
1882     TRACE("%p %i\n", hFont, bRedraw);
1883 
1884     infoPtr->hFont = hFont ? hFont : infoPtr->hDefaultFont;
1885 
1886     DeleteObject(infoPtr->hBoldFont);
1887     infoPtr->hBoldFont = TREEVIEW_CreateBoldFont(infoPtr->hFont);
1888     infoPtr->hUnderlineFont = TREEVIEW_CreateUnderlineFont(infoPtr->hFont);
1889 
1890     if (!infoPtr->bHeightSet)
1891         infoPtr->uItemHeight = TREEVIEW_NaturalHeight(infoPtr);
1892 
1893     if (uHeight != infoPtr->uItemHeight)
1894        TREEVIEW_RecalculateVisibleOrder(infoPtr, NULL);
1895 
1896     DPA_EnumCallback(infoPtr->items, TREEVIEW_ResetTextWidth, 0);
1897 
1898     TREEVIEW_UpdateSubTree(infoPtr, infoPtr->root);
1899     TREEVIEW_UpdateScrollBars(infoPtr);
1900 
1901     if (bRedraw)
1902         TREEVIEW_Invalidate(infoPtr, NULL);
1903 
1904     return 0;
1905 }
1906 
1907 
1908 static LRESULT
1909 TREEVIEW_GetLineColor(const TREEVIEW_INFO *infoPtr)
1910 {
1911     TRACE("\n");
1912     return (LRESULT)infoPtr->clrLine;
1913 }
1914 
1915 static LRESULT
1916 TREEVIEW_SetLineColor(TREEVIEW_INFO *infoPtr, COLORREF color)
1917 {
1918     COLORREF prevColor = infoPtr->clrLine;
1919 
1920     TRACE("\n");
1921     infoPtr->clrLine = color;
1922     return (LRESULT)prevColor;
1923 }
1924 
1925 
1926 static LRESULT
1927 TREEVIEW_GetTextColor(const TREEVIEW_INFO *infoPtr)
1928 {
1929     TRACE("\n");
1930     return (LRESULT)infoPtr->clrText;
1931 }
1932 
1933 static LRESULT
1934 TREEVIEW_SetTextColor(TREEVIEW_INFO *infoPtr, COLORREF color)
1935 {
1936     COLORREF prevColor = infoPtr->clrText;
1937 
1938     TRACE("\n");
1939     infoPtr->clrText = color;
1940 
1941     if (infoPtr->clrText != prevColor)
1942         TREEVIEW_Invalidate(infoPtr, NULL);
1943 
1944     return (LRESULT)prevColor;
1945 }
1946 
1947 
1948 static LRESULT
1949 TREEVIEW_GetBkColor(const TREEVIEW_INFO *infoPtr)
1950 {
1951     TRACE("\n");
1952     return (LRESULT)infoPtr->clrBk;
1953 }
1954 
1955 static LRESULT
1956 TREEVIEW_SetBkColor(TREEVIEW_INFO *infoPtr, COLORREF newColor)
1957 {
1958     COLORREF prevColor = infoPtr->clrBk;
1959 
1960     TRACE("\n");
1961     infoPtr->clrBk = newColor;
1962 
1963     if (newColor != prevColor)
1964         TREEVIEW_Invalidate(infoPtr, NULL);
1965 
1966     return (LRESULT)prevColor;
1967 }
1968 
1969 
1970 static LRESULT
1971 TREEVIEW_GetInsertMarkColor(const TREEVIEW_INFO *infoPtr)
1972 {
1973     TRACE("\n");
1974     return (LRESULT)infoPtr->clrInsertMark;
1975 }
1976 
1977 static LRESULT
1978 TREEVIEW_SetInsertMarkColor(TREEVIEW_INFO *infoPtr, COLORREF color)
1979 {
1980     COLORREF prevColor = infoPtr->clrInsertMark;
1981 
1982     TRACE("%x\n", color);
1983     infoPtr->clrInsertMark = color;
1984 
1985     return (LRESULT)prevColor;
1986 }
1987 
1988 
1989 static LRESULT
1990 TREEVIEW_SetInsertMark(TREEVIEW_INFO *infoPtr, BOOL wParam, HTREEITEM item)
1991 {
1992     TRACE("%d %p\n", wParam, item);
1993 
1994     if (!TREEVIEW_ValidItem(infoPtr, item))
1995         return 0;
1996 
1997     infoPtr->insertBeforeorAfter = wParam;
1998     infoPtr->insertMarkItem = item;
1999 
2000     TREEVIEW_Invalidate(infoPtr, NULL);
2001 
2002     return 1;
2003 }
2004 
2005 
2006 /************************************************************************
2007  * Some serious braindamage here. lParam is a pointer to both the
2008  * input HTREEITEM and the output RECT.
2009  */
2010 static LRESULT
2011 TREEVIEW_GetItemRect(const TREEVIEW_INFO *infoPtr, BOOL fTextRect, LPRECT lpRect)
2012 {
2013     TREEVIEW_ITEM *wineItem;
2014     const HTREEITEM *pItem = (HTREEITEM *)lpRect;
2015 
2016     TRACE("\n");
2017     /*
2018      * validate parameters
2019      */
2020     if (pItem == NULL)
2021         return FALSE;
2022 
2023     wineItem = *pItem;
2024     if (!TREEVIEW_ValidItem(infoPtr, wineItem) || !ISVISIBLE(wineItem))
2025         return FALSE;
2026 
2027     /*
2028      * If wParam is TRUE return the text size otherwise return
2029      * the whole item size
2030      */
2031     if (fTextRect)
2032     {
2033         /* Windows does not send TVN_GETDISPINFO here. */
2034 
2035         lpRect->top = wineItem->rect.top;
2036         lpRect->bottom = wineItem->rect.bottom;
2037 
2038         lpRect->left = wineItem->textOffset;
2039         if (!wineItem->textWidth)
2040                 TREEVIEW_ComputeTextWidth(infoPtr, wineItem, 0);
2041 
2042         lpRect->right = wineItem->textOffset + wineItem->textWidth + 4;
2043     }
2044     else
2045     {
2046         *lpRect = wineItem->rect;
2047     }
2048 
2049     TRACE("%s [%s]\n", fTextRect ? "text" : "item", wine_dbgstr_rect(lpRect));
2050 
2051     return TRUE;
2052 }
2053 
2054 static inline LRESULT
2055 TREEVIEW_GetVisibleCount(const TREEVIEW_INFO *infoPtr)
2056 {
2057     /* Surprise! This does not take integral height into account. */
2058     return infoPtr->clientHeight / infoPtr->uItemHeight;
2059 }
2060 
2061 
2062 static LRESULT
2063 TREEVIEW_GetItemT(const TREEVIEW_INFO *infoPtr, LPTVITEMEXW tvItem, BOOL isW)
2064 {
2065     TREEVIEW_ITEM *wineItem;
2066 
2067     wineItem = tvItem->hItem;
2068     if (!TREEVIEW_ValidItem(infoPtr, wineItem))
2069         return FALSE;
2070 
2071     TREEVIEW_UpdateDispInfo(infoPtr, wineItem, tvItem->mask);
2072 
2073     if (tvItem->mask & TVIF_CHILDREN)
2074     {
2075         if (wineItem->cChildren==I_CHILDRENCALLBACK)
2076             FIXME("I_CHILDRENCALLBACK not supported\n");
2077         tvItem->cChildren = wineItem->cChildren;
2078     }
2079 
2080     if (tvItem->mask & TVIF_HANDLE)
2081         tvItem->hItem = wineItem;
2082 
2083     if (tvItem->mask & TVIF_IMAGE)
2084         tvItem->iImage = wineItem->iImage;
2085 
2086     if (tvItem->mask & TVIF_INTEGRAL)
2087         tvItem->iIntegral = wineItem->iIntegral;
2088 
2089     /* undocumented: windows ignores TVIF_PARAM and
2090      * * always sets lParam
2091      */
2092     tvItem->lParam = wineItem->lParam;
2093 
2094     if (tvItem->mask & TVIF_SELECTEDIMAGE)
2095         tvItem->iSelectedImage = wineItem->iSelectedImage;
2096 
2097     if (tvItem->mask & TVIF_STATE)
2098         /* Careful here - Windows ignores the stateMask when you get the state
2099             That contradicts the documentation, but makes more common sense, masking
2100             retrieval in this way seems overkill */
2101         tvItem->state = wineItem->state;
2102 
2103     if (tvItem->mask & TVIF_TEXT)
2104     {
2105         if (wineItem->pszText == NULL)
2106         {
2107             if (tvItem->cchTextMax > 0)
2108                 tvItem->pszText[0] = '\0';
2109         }
2110         else if (isW)
2111         {
2112             if (wineItem->pszText == LPSTR_TEXTCALLBACKW)
2113             {
2114                 tvItem->pszText = LPSTR_TEXTCALLBACKW;
2115                 FIXME(" GetItem called with LPSTR_TEXTCALLBACK\n");
2116             }
2117             else
2118             {
2119                 lstrcpynW(tvItem->pszText, wineItem->pszText, tvItem->cchTextMax);
2120             }
2121         }
2122         else
2123         {
2124             if (wineItem->pszText == LPSTR_TEXTCALLBACKW)
2125             {
2126                 tvItem->pszText = (LPWSTR)LPSTR_TEXTCALLBACKA;
2127                 FIXME(" GetItem called with LPSTR_TEXTCALLBACK\n");
2128             }
2129             else
2130             {
2131                 WideCharToMultiByte(CP_ACP, 0, wineItem->pszText, -1,
2132                                     (LPSTR)tvItem->pszText, tvItem->cchTextMax, NULL, NULL);
2133             }
2134         }
2135     }
2136     TRACE("item <%p>, txt %p, img %p, mask %x\n",
2137           wineItem, tvItem->pszText, &tvItem->iImage, tvItem->mask);
2138 
2139     return TRUE;
2140 }
2141 
2142 /* Beware MSDN Library Visual Studio 6.0. It says -1 on failure, 0 on success,
2143  * which is wrong. */
2144 static LRESULT
2145 TREEVIEW_SetItemT(TREEVIEW_INFO *infoPtr, const TVITEMEXW *tvItem, BOOL isW)
2146 {
2147     TREEVIEW_ITEM *wineItem;
2148     TREEVIEW_ITEM originalItem;
2149 
2150     wineItem = tvItem->hItem;
2151 
2152     TRACE("item %d,mask %x\n", TREEVIEW_GetItemIndex(infoPtr, wineItem),
2153           tvItem->mask);
2154 
2155     if (!TREEVIEW_ValidItem(infoPtr, wineItem))
2156         return FALSE;
2157 
2158     /* store the original item values */
2159     originalItem = *wineItem;
2160 
2161     if (!TREEVIEW_DoSetItemT(infoPtr, wineItem, tvItem, isW))
2162         return FALSE;
2163 
2164     /* If the text or TVIS_BOLD was changed, and it is visible, recalculate. */
2165     if ((tvItem->mask & TVIF_TEXT
2166          || (tvItem->mask & TVIF_STATE && tvItem->stateMask & TVIS_BOLD))
2167         && ISVISIBLE(wineItem))
2168     {
2169         TREEVIEW_UpdateDispInfo(infoPtr, wineItem, TVIF_TEXT);
2170         TREEVIEW_ComputeTextWidth(infoPtr, wineItem, 0);
2171     }
2172 
2173     if (tvItem->mask != 0 && ISVISIBLE(wineItem))
2174     {
2175         /* The refresh updates everything, but we can't wait until then. */
2176         TREEVIEW_ComputeItemInternalMetrics(infoPtr, wineItem);
2177 
2178         /* if any of the item's values changed and it's not a callback, redraw the item */
2179         if (item_changed(&originalItem, wineItem, tvItem))
2180         {
2181             if (tvItem->mask & TVIF_INTEGRAL)
2182             {
2183                 TREEVIEW_RecalculateVisibleOrder(infoPtr, wineItem);
2184                 TREEVIEW_UpdateScrollBars(infoPtr);
2185 
2186                 TREEVIEW_Invalidate(infoPtr, NULL);
2187             }
2188             else
2189             {
2190                 TREEVIEW_UpdateScrollBars(infoPtr);
2191                 TREEVIEW_Invalidate(infoPtr, wineItem);
2192             }
2193         }
2194     }
2195 
2196     return TRUE;
2197 }
2198 
2199 static LRESULT
2200 TREEVIEW_GetItemState(const TREEVIEW_INFO *infoPtr, HTREEITEM wineItem, UINT mask)
2201 {
2202     TRACE("\n");
2203 
2204     if (!wineItem || !TREEVIEW_ValidItem(infoPtr, wineItem))
2205         return 0;
2206 
2207     return (wineItem->state & mask);
2208 }
2209 
2210 static LRESULT
2211 TREEVIEW_GetNextItem(const TREEVIEW_INFO *infoPtr, UINT which, HTREEITEM wineItem)
2212 {
2213     TREEVIEW_ITEM *retval;
2214 
2215     retval = 0;
2216 
2217     /* handle all the global data here */
2218     switch (which)
2219     {
2220     case TVGN_CHILD:            /* Special case: child of 0 is root */
2221         if (wineItem)
2222             break;
2223         /* fall through */
2224     case TVGN_ROOT:
2225         retval = infoPtr->root->firstChild;
2226         break;
2227 
2228     case TVGN_CARET:
2229         retval = infoPtr->selectedItem;
2230         break;
2231 
2232     case TVGN_FIRSTVISIBLE:
2233         retval = infoPtr->firstVisible;
2234         break;
2235 
2236     case TVGN_DROPHILITE:
2237         retval = infoPtr->dropItem;
2238         break;
2239 
2240     case TVGN_LASTVISIBLE:
2241         retval = TREEVIEW_GetLastListItem(infoPtr, infoPtr->root);
2242         break;
2243     }
2244 
2245     if (retval)
2246     {
2247         TRACE("flags:%x, returns %p\n", which, retval);
2248         return (LRESULT)retval;
2249     }
2250 
2251     if (wineItem == TVI_ROOT) wineItem = infoPtr->root;
2252 
2253     if (!TREEVIEW_ValidItem(infoPtr, wineItem))
2254         return FALSE;
2255 
2256     switch (which)
2257     {
2258     case TVGN_NEXT:
2259         retval = wineItem->nextSibling;
2260         break;
2261     case TVGN_PREVIOUS:
2262         retval = wineItem->prevSibling;
2263         break;
2264     case TVGN_PARENT:
2265         retval = (wineItem->parent != infoPtr->root) ? wineItem->parent : NULL;
2266         break;
2267     case TVGN_CHILD:
2268         retval = wineItem->firstChild;
2269         break;
2270     case TVGN_NEXTVISIBLE:
2271         retval = TREEVIEW_GetNextListItem(infoPtr, wineItem);
2272         break;
2273     case TVGN_PREVIOUSVISIBLE:
2274         retval = TREEVIEW_GetPrevListItem(infoPtr, wineItem);
2275         break;
2276     default:
2277         TRACE("Unknown msg %x,item %p\n", which, wineItem);
2278         break;
2279     }
2280 
2281     TRACE("flags:%x, item %p;returns %p\n", which, wineItem, retval);
2282     return (LRESULT)retval;
2283 }
2284 
2285 
2286 static LRESULT
2287 TREEVIEW_GetCount(const TREEVIEW_INFO *infoPtr)
2288 {
2289     TRACE(" %d\n", infoPtr->uNumItems);
2290     return (LRESULT)infoPtr->uNumItems;
2291 }
2292 
2293 static VOID
2294 TREEVIEW_ToggleItemState(const TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *item)
2295 {
2296     if (infoPtr->dwStyle & TVS_CHECKBOXES)
2297     {
2298         static const unsigned int state_table[] = { 0, 2, 1 };
2299 
2300         unsigned int state;
2301 
2302         state = STATEIMAGEINDEX(item->state);
2303         TRACE("state:%x\n", state);
2304         item->state &= ~TVIS_STATEIMAGEMASK;
2305 
2306         if (state < 3)
2307             state = state_table[state];
2308 
2309         item->state |= INDEXTOSTATEIMAGEMASK(state);
2310 
2311         TRACE("state:%x\n", state);
2312         TREEVIEW_Invalidate(infoPtr, item);
2313     }
2314 }
2315 
2316 
2317 /* Painting *************************************************************/
2318 
2319 /* Draw the lines and expand button for an item. Also draws one section
2320  * of the line from item's parent to item's parent's next sibling. */
2321 static void
2322 TREEVIEW_DrawItemLines(const TREEVIEW_INFO *infoPtr, HDC hdc, const TREEVIEW_ITEM *item)
2323 {
2324     LONG centerx, centery;
2325     BOOL lar = ((infoPtr->dwStyle
2326                  & (TVS_LINESATROOT|TVS_HASLINES|TVS_HASBUTTONS))
2327                 > TVS_LINESATROOT);
2328     HBRUSH hbr, hbrOld;
2329     COLORREF clrBk = GETBKCOLOR(infoPtr->clrBk);
2330 
2331     if (!lar && item->iLevel == 0)
2332         return;
2333 
2334     hbr    = CreateSolidBrush(clrBk);
2335     hbrOld = SelectObject(hdc, hbr);
2336 
2337     centerx = (item->linesOffset + item->stateOffset) / 2;
2338     centery = (item->rect.top + item->rect.bottom) / 2;
2339 
2340     if (infoPtr->dwStyle & TVS_HASLINES)
2341     {
2342         HPEN hOldPen, hNewPen;
2343         HTREEITEM parent;
2344         LOGBRUSH lb;
2345 
2346         /* Get a dotted grey pen */
2347         lb.lbStyle = BS_SOLID;
2348         lb.lbColor = GETLINECOLOR(infoPtr->clrLine);
2349         hNewPen = ExtCreatePen(PS_COSMETIC|PS_ALTERNATE, 1, &lb, 0, NULL);
2350         hOldPen = SelectObject(hdc, hNewPen);
2351 
2352         /* Make sure the center is on a dot (using +2 instead
2353          * of +1 gives us pixel-by-pixel compat with native) */
2354         centery = (centery + 2) & ~1;
2355 
2356         MoveToEx(hdc, item->stateOffset, centery, NULL);
2357         LineTo(hdc, centerx - 1, centery);
2358 
2359         if (item->prevSibling || item->parent != infoPtr->root)
2360         {
2361             MoveToEx(hdc, centerx, item->rect.top, NULL);
2362             LineTo(hdc, centerx, centery);
2363         }
2364 
2365         if (item->nextSibling)
2366         {
2367             MoveToEx(hdc, centerx, centery, NULL);
2368             LineTo(hdc, centerx, item->rect.bottom + 1);
2369         }
2370 
2371         /* Draw the line from our parent to its next sibling. */
2372         parent = item->parent;
2373         while (parent != infoPtr->root)
2374         {
2375             int pcenterx = (parent->linesOffset + parent->stateOffset) / 2;
2376 
2377             if (parent->nextSibling
2378                 /* skip top-levels unless TVS_LINESATROOT */
2379                 && parent->stateOffset > parent->linesOffset)
2380             {
2381                 MoveToEx(hdc, pcenterx, item->rect.top, NULL);
2382                 LineTo(hdc, pcenterx, item->rect.bottom + 1);
2383             }
2384 
2385             parent = parent->parent;
2386         }
2387 
2388         SelectObject(hdc, hOldPen);
2389         DeleteObject(hNewPen);
2390     }
2391 
2392     /*
2393      * Display the (+/-) signs
2394      */
2395 
2396     if (infoPtr->dwStyle & TVS_HASBUTTONS)
2397     {
2398         if (item->cChildren)
2399         {
2400             HTHEME theme = GetWindowTheme(infoPtr->hwnd);
2401             if (theme)
2402             {
2403                 RECT glyphRect = item->rect;
2404                 glyphRect.left = item->linesOffset;
2405                 glyphRect.right = item->stateOffset;
2406                 DrawThemeBackground (theme, hdc, TVP_GLYPH,
2407                     (item->state & TVIS_EXPANDED) ? GLPS_OPENED : GLPS_CLOSED,
2408                     &glyphRect, NULL);
2409             }
2410             else
2411             {
2412                 LONG height = item->rect.bottom - item->rect.top;
2413                 LONG width  = item->stateOffset - item->linesOffset;
2414                 LONG rectsize = min(height, width) / 4;
2415                 /* plussize = ceil(rectsize * 3/4) */
2416                 LONG plussize = (rectsize + 1) * 3 / 4;
2417 
2418                 HPEN new_pen  = CreatePen(PS_SOLID, 0, GETLINECOLOR(infoPtr->clrLine));
2419                 HPEN old_pen  = SelectObject(hdc, new_pen);
2420 
2421                 Rectangle(hdc, centerx - rectsize - 1, centery - rectsize - 1,
2422                           centerx + rectsize + 2, centery + rectsize + 2);
2423 
2424                 SelectObject(hdc, old_pen);
2425                 DeleteObject(new_pen);
2426 
2427                 /* draw +/- signs with current text color */
2428                 new_pen = CreatePen(PS_SOLID, 0, GETTXTCOLOR(infoPtr->clrText));
2429                 old_pen = SelectObject(hdc, new_pen);
2430 
2431                 if (height < 18 || width < 18)
2432                 {
2433                     MoveToEx(hdc, centerx - plussize + 1, centery, NULL);
2434                     LineTo(hdc, centerx + plussize, centery);
2435     
2436                     if (!(item->state & TVIS_EXPANDED))
2437                     {
2438                         MoveToEx(hdc, centerx, centery - plussize + 1, NULL);
2439                         LineTo(hdc, centerx, centery + plussize);
2440                     }
2441                 }
2442                 else
2443                 {
2444                     Rectangle(hdc, centerx - plussize + 1, centery - 1,
2445                     centerx + plussize, centery + 2);
2446     
2447                     if (!(item->state & TVIS_EXPANDED))
2448                     {
2449                         Rectangle(hdc, centerx - 1, centery - plussize + 1,
2450                         centerx + 2, centery + plussize);
2451                         SetPixel(hdc, centerx - 1, centery, clrBk);
2452                         SetPixel(hdc, centerx + 1, centery, clrBk);
2453                     }
2454                 }
2455 
2456                 SelectObject(hdc, old_pen);
2457                 DeleteObject(new_pen);
2458             }
2459         }
2460     }
2461     SelectObject(hdc, hbrOld);
2462     DeleteObject(hbr);
2463 }
2464 
2465 static void
2466 TREEVIEW_DrawItem(const TREEVIEW_INFO *infoPtr, HDC hdc, TREEVIEW_ITEM *wineItem)
2467 {
2468     INT cditem;
2469     HFONT hOldFont;
2470     COLORREF oldTextColor, oldTextBkColor;
2471     int centery;
2472     BOOL inFocus = (GetFocus() == infoPtr->hwnd);
2473     NMTVCUSTOMDRAW nmcdhdr;
2474 
2475     TREEVIEW_UpdateDispInfo(infoPtr, wineItem, CALLBACK_MASK_ALL);
2476 
2477     /* - If item is drop target or it is selected and window is in focus -
2478      * use blue background (COLOR_HIGHLIGHT).
2479      * - If item is selected, window is not in focus, but it has style
2480      * TVS_SHOWSELALWAYS - use grey background (COLOR_BTNFACE)
2481      * - Otherwise - use background color
2482      */
2483     if ((wineItem->state & TVIS_DROPHILITED) || ((wineItem == infoPtr->focusedItem) && !(wineItem->state & TVIS_SELECTED)) ||
2484         ((wineItem->state & TVIS_SELECTED) && (!infoPtr->focusedItem) &&
2485          (inFocus || (infoPtr->dwStyle & TVS_SHOWSELALWAYS))))
2486     {
2487         if ((wineItem->state & TVIS_DROPHILITED) || inFocus)
2488         {
2489             nmcdhdr.clrTextBk = comctl32_color.clrHighlight;
2490             nmcdhdr.clrText   = comctl32_color.clrHighlightText;
2491         }
2492         else
2493         {
2494             nmcdhdr.clrTextBk = comctl32_color.clrBtnFace;
2495             nmcdhdr.clrText   = GETTXTCOLOR(infoPtr->clrText);
2496         }
2497     }
2498     else
2499     {
2500         nmcdhdr.clrTextBk = GETBKCOLOR(infoPtr->clrBk);
2501         if ((infoPtr->dwStyle & TVS_TRACKSELECT) && (wineItem == infoPtr->hotItem))
2502             nmcdhdr.clrText = comctl32_color.clrHighlight;
2503         else
2504             nmcdhdr.clrText = GETTXTCOLOR(infoPtr->clrText);
2505     }
2506 
2507     hOldFont = SelectObject(hdc, TREEVIEW_FontForItem(infoPtr, wineItem));
2508 
2509     /* The custom draw handler can query the text rectangle,
2510      * so get ready. */
2511     /* should already be known, set to 0 when changed */
2512     if (!wineItem->textWidth)
2513         TREEVIEW_ComputeTextWidth(infoPtr, wineItem, hdc);
2514 
2515     cditem = 0;
2516 
2517     if (infoPtr->cdmode & CDRF_NOTIFYITEMDRAW)
2518     {
2519         cditem = TREEVIEW_SendCustomDrawItemNotify
2520             (infoPtr, hdc, wineItem, CDDS_ITEMPREPAINT, &nmcdhdr);
2521         TRACE("prepaint:cditem-app returns 0x%x\n", cditem);
2522 
2523         if (cditem & CDRF_SKIPDEFAULT)
2524         {
2525             SelectObject(hdc, hOldFont);
2526             return;
2527         }
2528     }
2529 
2530     if (cditem & CDRF_NEWFONT)
2531         TREEVIEW_ComputeTextWidth(infoPtr, wineItem, hdc);
2532 
2533     TREEVIEW_DrawItemLines(infoPtr, hdc, wineItem);
2534 
2535     /* Set colors. Custom draw handler can change these so we do this after it. */
2536     oldTextColor = SetTextColor(hdc, nmcdhdr.clrText);
2537     oldTextBkColor = SetBkColor(hdc, nmcdhdr.clrTextBk);
2538 
2539     centery = (wineItem->rect.top + wineItem->rect.bottom) / 2;
2540 
2541     /*
2542      * Display the images associated with this item
2543      */
2544     {
2545         INT imageIndex;
2546 
2547         /* State images are displayed to the left of the Normal image
2548          * image number is in state; zero should be `display no image'.
2549          */
2550         imageIndex = STATEIMAGEINDEX(wineItem->state);
2551 
2552         if (infoPtr->himlState && imageIndex)
2553         {
2554             ImageList_Draw(infoPtr->himlState, imageIndex, hdc,
2555                            wineItem->stateOffset,
2556                            centery - infoPtr->stateImageHeight / 2,
2557                            ILD_NORMAL);
2558         }
2559 
2560         /* Now, draw the normal image; can be either selected or
2561          * non-selected image.
2562          */
2563 
2564         if ((wineItem->state & TVIS_SELECTED) && (wineItem->iSelectedImage >= 0))
2565         {
2566             /* The item is currently selected */
2567             imageIndex = wineItem->iSelectedImage;
2568         }
2569         else
2570         {
2571             /* The item is not selected */
2572             imageIndex = wineItem->iImage;
2573         }
2574 
2575         if (infoPtr->himlNormal)
2576         {
2577             int ovlIdx = wineItem->state & TVIS_OVERLAYMASK;
2578 
2579             ImageList_Draw(infoPtr->himlNormal, imageIndex, hdc,
2580                            wineItem->imageOffset,
2581                            centery - infoPtr->normalImageHeight / 2,
2582                            ILD_NORMAL | ovlIdx);
2583         }
2584     }
2585 
2586 
2587     /*
2588      * Display the text associated with this item
2589      */
2590 
2591     /* Don't paint item's text if it's being edited */
2592     if (!infoPtr->hwndEdit || (infoPtr->selectedItem != wineItem))
2593     {
2594         if (wineItem->pszText)
2595         {
2596             RECT rcText;
2597 
2598             rcText.top = wineItem->rect.top;
2599             rcText.bottom = wineItem->rect.bottom;
2600             rcText.left = wineItem->textOffset;
2601             rcText.right = rcText.left + wineItem->textWidth + 4;
2602 
2603             TRACE("drawing text %s at (%s)\n",
2604                   debugstr_w(wineItem->pszText), wine_dbgstr_rect(&rcText));
2605 
2606             /* Draw it */
2607             ExtTextOutW(hdc, rcText.left + 2, rcText.top + 1,
2608                         ETO_CLIPPED | ETO_OPAQUE,
2609                         &rcText,
2610                         wineItem->pszText,
2611                         lstrlenW(wineItem->pszText),
2612                         NULL);
2613                         
2614             /* Draw the box around the selected item */
2615             if ((wineItem == infoPtr->selectedItem) && inFocus)
2616             {
2617                 DrawFocusRect(hdc,&rcText);
2618             }
2619 
2620         }
2621     }
2622 
2623     /* Draw insertion mark if necessary */
2624 
2625     if (infoPtr->insertMarkItem)
2626         TRACE("item:%d,mark:%p\n",
2627               TREEVIEW_GetItemIndex(infoPtr, wineItem),
2628               infoPtr->insertMarkItem);
2629 
2630     if (wineItem == infoPtr->insertMarkItem)
2631     {
2632         HPEN hNewPen, hOldPen;
2633         int offset;
2634         int left, right;
2635 
2636         hNewPen = CreatePen(PS_SOLID, 2, GETINSCOLOR(infoPtr->clrInsertMark));
2637         hOldPen = SelectObject(hdc, hNewPen);
2638 
2639         if (infoPtr->insertBeforeorAfter)
2640             offset = wineItem->rect.bottom - 1;
2641         else
2642             offset = wineItem->rect.top + 1;
2643 
2644         left = wineItem->textOffset - 2;
2645         right = wineItem->textOffset + wineItem->textWidth + 2;
2646 
2647         MoveToEx(hdc, left, offset - 3, NULL);
2648         LineTo(hdc, left, offset + 4);
2649 
2650         MoveToEx(hdc, left, offset, NULL);
2651         LineTo(hdc, right + 1, offset);
2652 
2653         MoveToEx(hdc, right, offset + 3, NULL);
2654         LineTo(hdc, right, offset - 4);
2655 
2656         SelectObject(hdc, hOldPen);
2657         DeleteObject(hNewPen);
2658     }
2659 
2660     if (cditem & CDRF_NOTIFYPOSTPAINT)
2661     {
2662         cditem = TREEVIEW_SendCustomDrawItemNotify
2663             (infoPtr, hdc, wineItem, CDDS_ITEMPOSTPAINT, &nmcdhdr);
2664         TRACE("postpaint:cditem-app returns 0x%x\n", cditem);
2665     }
2666 
2667     /* Restore the hdc state */
2668     SetTextColor(hdc, oldTextColor);
2669     SetBkColor(hdc, oldTextBkColor);
2670     SelectObject(hdc, hOldFont);
2671 }
2672 
2673 /* Computes treeHeight and treeWidth and updates the scroll bars.
2674  */
2675 static void
2676 TREEVIEW_UpdateScrollBars(TREEVIEW_INFO *infoPtr)
2677 {
2678     TREEVIEW_ITEM *wineItem;
2679     HWND hwnd = infoPtr->hwnd;
2680     BOOL vert = FALSE;
2681     BOOL horz = FALSE;
2682     SCROLLINFO si;
2683     LONG scrollX = infoPtr->scrollX;
2684 
2685     infoPtr->treeWidth = 0;
2686     infoPtr->treeHeight = 0;
2687 
2688     /* We iterate through all visible items in order to get the tree height
2689      * and width */
2690     wineItem = infoPtr->root->firstChild;
2691 
2692     while (wineItem != NULL)
2693     {
2694         if (ISVISIBLE(wineItem))
2695         {
2696             /* actually we draw text at textOffset + 2 */
2697             if (2+wineItem->textOffset+wineItem->textWidth > infoPtr->treeWidth)
2698                 infoPtr->treeWidth = wineItem->textOffset+wineItem->textWidth+2;
2699 
2700             /* This is scroll-adjusted, but we fix this below. */
2701             infoPtr->treeHeight = wineItem->rect.bottom;
2702         }
2703 
2704         wineItem = TREEVIEW_GetNextListItem(infoPtr, wineItem);
2705     }
2706 
2707     /* Fix the scroll adjusted treeHeight and treeWidth. */
2708     if (infoPtr->root->firstChild)
2709         infoPtr->treeHeight -= infoPtr->root->firstChild->rect.top;
2710 
2711     infoPtr->treeWidth += infoPtr->scrollX;
2712 
2713     if (infoPtr->dwStyle & TVS_NOSCROLL) return;
2714 
2715     /* Adding one scroll bar may take up enough space that it forces us
2716      * to add the other as well. */
2717     if (infoPtr->treeHeight > infoPtr->clientHeight)
2718     {
2719         vert = TRUE;
2720 
2721         if (infoPtr->treeWidth
2722             > infoPtr->clientWidth - GetSystemMetrics(SM_CXVSCROLL))
2723             horz = TRUE;
2724     }
2725     else if (infoPtr->treeWidth > infoPtr->clientWidth || infoPtr->scrollX > 0)
2726         horz = TRUE;
2727 
2728     if (!vert && horz && infoPtr->treeHeight
2729         > infoPtr->clientHeight - GetSystemMetrics(SM_CYVSCROLL))
2730         vert = TRUE;
2731 
2732     if (horz && (infoPtr->dwStyle & TVS_NOHSCROLL)) horz = FALSE;
2733 
2734     si.cbSize = sizeof(SCROLLINFO);
2735     si.fMask  = SIF_POS|SIF_RANGE|SIF_PAGE;
2736     si.nMin   = 0;
2737 
2738     if (vert)
2739     {
2740         si.nPage = TREEVIEW_GetVisibleCount(infoPtr);
2741        if ( si.nPage && NULL != infoPtr->firstVisible)
2742        {
2743            si.nPos  = infoPtr->firstVisible->visibleOrder;
2744            si.nMax  = infoPtr->maxVisibleOrder - 1;
2745 
2746            SetScrollInfo(hwnd, SB_VERT, &si, TRUE);
2747 
2748            if (!(infoPtr->uInternalStatus & TV_VSCROLL))
2749                ShowScrollBar(hwnd, SB_VERT, TRUE);
2750            infoPtr->uInternalStatus |= TV_VSCROLL;
2751        }
2752        else
2753        {
2754            if (infoPtr->uInternalStatus & TV_VSCROLL)
2755                ShowScrollBar(hwnd, SB_VERT, FALSE);
2756            infoPtr->uInternalStatus &= ~TV_VSCROLL;
2757        }
2758     }
2759     else
2760     {
2761         if (infoPtr->uInternalStatus & TV_VSCROLL)
2762             ShowScrollBar(hwnd, SB_VERT, FALSE);
2763         infoPtr->uInternalStatus &= ~TV_VSCROLL;
2764     }
2765 
2766     if (horz)
2767     {
2768         si.nPage = infoPtr->clientWidth;
2769         si.nPos  = infoPtr->scrollX;
2770         si.nMax  = infoPtr->treeWidth - 1;
2771 
2772         if (si.nPos > si.nMax - max( si.nPage-1, 0 ))
2773         {
2774            si.nPos = si.nMax - max( si.nPage-1, 0 );
2775            scrollX = si.nPos;
2776         }
2777 
2778         if (!(infoPtr->uInternalStatus & TV_HSCROLL))
2779             ShowScrollBar(hwnd, SB_HORZ, TRUE);
2780         infoPtr->uInternalStatus |= TV_HSCROLL;
2781 
2782         SetScrollInfo(hwnd, SB_HORZ, &si, TRUE);
2783         TREEVIEW_HScroll(infoPtr,
2784                         MAKEWPARAM(SB_THUMBPOSITION, scrollX));
2785     }
2786     else
2787     {
2788         if (infoPtr->uInternalStatus & TV_HSCROLL)
2789             ShowScrollBar(hwnd, SB_HORZ, FALSE);
2790         infoPtr->uInternalStatus &= ~TV_HSCROLL;
2791 
2792         scrollX = 0;
2793         if (infoPtr->scrollX != 0)
2794         {
2795             TREEVIEW_HScroll(infoPtr,
2796                             MAKEWPARAM(SB_THUMBPOSITION, scrollX));
2797         }
2798     }
2799 
2800     if (!horz)
2801         infoPtr->uInternalStatus &= ~TV_HSCROLL;
2802 }
2803 
2804 static void
2805 TREEVIEW_FillBkgnd(const TREEVIEW_INFO *infoPtr, HDC hdc, const RECT *rc)
2806 {
2807     HBRUSH hBrush;
2808     COLORREF clrBk = GETBKCOLOR(infoPtr->clrBk);
2809 
2810     hBrush =  CreateSolidBrush(clrBk);
2811     FillRect(hdc, rc, hBrush);
2812     DeleteObject(hBrush);
2813 }
2814 
2815 /* CtrlSpy doesn't mention this, but CorelDRAW's object manager needs it. */
2816 static LRESULT
2817 TREEVIEW_EraseBackground(const TREEVIEW_INFO *infoPtr, HDC hdc)
2818 {
2819     RECT rect;
2820 
2821     TRACE("%p\n", infoPtr);
2822 
2823     GetClientRect(infoPtr->hwnd, &rect);
2824     TREEVIEW_FillBkgnd(infoPtr, hdc, &rect);
2825 
2826     return 1;
2827 }
2828 
2829 static void
2830 TREEVIEW_Refresh(TREEVIEW_INFO *infoPtr, HDC hdc, const RECT *rc)
2831 {
2832     HWND hwnd = infoPtr->hwnd;
2833     RECT rect = *rc;
2834     TREEVIEW_ITEM *wineItem;
2835 
2836     if (infoPtr->clientHeight == 0 || infoPtr->clientWidth == 0)
2837     {
2838         TRACE("empty window\n");
2839         return;
2840     }
2841 
2842     infoPtr->cdmode = TREEVIEW_SendCustomDrawNotify(infoPtr, CDDS_PREPAINT,
2843                                                     hdc, rect);
2844 
2845     if (infoPtr->cdmode == CDRF_SKIPDEFAULT)
2846     {
2847         ReleaseDC(hwnd, hdc);
2848         return;
2849     }
2850 
2851     for (wineItem = infoPtr->root->firstChild;
2852          wineItem != NULL;
2853          wineItem = TREEVIEW_GetNextListItem(infoPtr, wineItem))
2854     {
2855         if (ISVISIBLE(wineItem))
2856         {
2857             /* Avoid unneeded calculations */
2858             if (wineItem->rect.top > rect.bottom)
2859                 break;
2860             if (wineItem->rect.bottom < rect.top)
2861                 continue;
2862 
2863             TREEVIEW_DrawItem(infoPtr, hdc, wineItem);
2864         }
2865     }
2866 
2867     TREEVIEW_UpdateScrollBars(infoPtr);
2868 
2869     if (infoPtr->cdmode & CDRF_NOTIFYPOSTPAINT)
2870         infoPtr->cdmode =
2871             TREEVIEW_SendCustomDrawNotify(infoPtr, CDDS_POSTPAINT, hdc, rect);
2872 }
2873 
2874 static inline void
2875 TREEVIEW_InvalidateItem(const TREEVIEW_INFO *infoPtr, const TREEVIEW_ITEM *item)
2876 {
2877     if (item) InvalidateRect(infoPtr->hwnd, &item->rect, TRUE);
2878 }
2879 
2880 static void
2881 TREEVIEW_Invalidate(const TREEVIEW_INFO *infoPtr, const TREEVIEW_ITEM *item)
2882 {
2883     if (item)
2884         InvalidateRect(infoPtr->hwnd, &item->rect, TRUE);
2885     else
2886         InvalidateRect(infoPtr->hwnd, NULL, TRUE);
2887 }
2888 
2889 static LRESULT
2890 TREEVIEW_Paint(TREEVIEW_INFO *infoPtr, HDC hdc_ref)
2891 {
2892     HDC hdc;
2893     PAINTSTRUCT ps;
2894     RECT rc;
2895 
2896     TRACE("\n");
2897 
2898     if (hdc_ref)
2899     {
2900         hdc = hdc_ref;
2901         GetClientRect(infoPtr->hwnd, &rc);
2902     }
2903     else
2904     {
2905         hdc = BeginPaint(infoPtr->hwnd, &ps);
2906         rc  = ps.rcPaint;
2907         if(ps.fErase)
2908             TREEVIEW_FillBkgnd(infoPtr, hdc, &rc);
2909     }
2910 
2911     if(infoPtr->bRedraw) /* WM_SETREDRAW sets bRedraw */
2912         TREEVIEW_Refresh(infoPtr, hdc, &rc);
2913 
2914     if (!hdc_ref)
2915         EndPaint(infoPtr->hwnd, &ps);
2916 
2917     return 0;
2918 }
2919 
2920 static LRESULT
2921 TREEVIEW_PrintClient(TREEVIEW_INFO *infoPtr, HDC hdc, DWORD options)
2922 {
2923     FIXME("Partial Stub: (hdc=%p options=0x%08x)\n", hdc, options);
2924 
2925     if ((options & PRF_CHECKVISIBLE) && !IsWindowVisible(infoPtr->hwnd))
2926         return 0;
2927 
2928     if (options & PRF_ERASEBKGND)
2929         TREEVIEW_EraseBackground(infoPtr, hdc);
2930 
2931     if (options & PRF_CLIENT)
2932     {
2933         RECT rc;
2934         GetClientRect(infoPtr->hwnd, &rc);
2935         TREEVIEW_Refresh(infoPtr, hdc, &rc);
2936     }
2937 
2938     return 0;
2939 }
2940 
2941 /* Sorting **************************************************************/
2942 
2943 /***************************************************************************
2944  * Forward the DPA local callback to the treeview owner callback
2945  */
2946 static INT WINAPI
2947 TREEVIEW_CallBackCompare(const TREEVIEW_ITEM *first, const TREEVIEW_ITEM *second,
2948                          const TVSORTCB *pCallBackSort)
2949 {
2950     /* Forward the call to the client-defined callback */
2951     return pCallBackSort->lpfnCompare(first->lParam,
2952                                       second->lParam,
2953                                       pCallBackSort->lParam);
2954 }
2955 
2956 /***************************************************************************
2957  * Treeview native sort routine: sort on item text.
2958  */
2959 static INT WINAPI
2960 TREEVIEW_SortOnName(TREEVIEW_ITEM *first, TREEVIEW_ITEM *second,
2961                     const TREEVIEW_INFO *infoPtr)
2962 {
2963     TREEVIEW_UpdateDispInfo(infoPtr, first, TVIF_TEXT);
2964     TREEVIEW_UpdateDispInfo(infoPtr, second, TVIF_TEXT);
2965 
2966     if(first->pszText && second->pszText)
2967         return lstrcmpiW(first->pszText, second->pszText);
2968     else if(first->pszText)
2969         return -1;
2970     else if(second->pszText)
2971         return 1;
2972     else
2973         return 0;
2974 }
2975 
2976 /* Returns the number of physical children belonging to item. */
2977 static INT
2978 TREEVIEW_CountChildren(const TREEVIEW_ITEM *item)
2979 {
2980     INT cChildren = 0;
2981     HTREEITEM hti;
2982 
2983     for (hti = item->firstChild; hti != NULL; hti = hti->nextSibling)
2984         cChildren++;
2985 
2986     return cChildren;
2987 }
2988 
2989 /* Returns a DPA containing a pointer to each physical child of item in
2990  * sibling order. If item has no children, an empty DPA is returned. */
2991 static HDPA
2992 TREEVIEW_BuildChildDPA(const TREEVIEW_ITEM *item)
2993 {
2994     HTREEITEM child = item->firstChild;
2995 
2996     HDPA list = DPA_Create(8);
2997     if (list == 0) return NULL;
2998 
2999     for (child = item->firstChild; child != NULL; child = child->nextSibling)
3000     {
3001         if (DPA_InsertPtr(list, INT_MAX, child) == -1)
3002         {
3003             DPA_Destroy(list);
3004             return NULL;
3005         }
3006     }
3007 
3008     return list;
3009 }
3010 
3011 /***************************************************************************
3012  * Setup the treeview structure with regards of the sort method
3013  * and sort the children of the TV item specified in lParam
3014  * fRecurse: currently unused. Should be zero.
3015  * parent: if pSort!=NULL, should equal pSort->hParent.
3016  *         otherwise, item which child items are to be sorted.
3017  * pSort:  sort method info. if NULL, sort on item text.
3018  *         if non-NULL, sort on item's lParam content, and let the
3019  *         application decide what that means. See also TVM_SORTCHILDRENCB.
3020  */
3021 
3022 static LRESULT
3023 TREEVIEW_Sort(TREEVIEW_INFO *infoPtr, HTREEITEM parent,
3024               LPTVSORTCB pSort)
3025 {
3026     INT cChildren;
3027     PFNDPACOMPARE pfnCompare;
3028     LPARAM lpCompare;
3029 
3030     /* undocumented feature: TVI_ROOT or NULL means `sort the whole tree' */
3031     if (parent == TVI_ROOT || parent == NULL)
3032         parent = infoPtr->root;
3033 
3034     /* Check for a valid handle to the parent item */
3035     if (!TREEVIEW_ValidItem(infoPtr, parent))
3036     {
3037         ERR("invalid item hParent=%p\n", parent);
3038         return FALSE;
3039     }
3040 
3041     if (pSort)
3042     {
3043         pfnCompare = (PFNDPACOMPARE)TREEVIEW_CallBackCompare;
3044         lpCompare = (LPARAM)pSort;
3045     }
3046     else
3047     {
3048         pfnCompare = (PFNDPACOMPARE)TREEVIEW_SortOnName;
3049         lpCompare = (LPARAM)infoPtr;
3050     }
3051 
3052     cChildren = TREEVIEW_CountChildren(parent);
3053 
3054     /* Make sure there is something to sort */
3055     if (cChildren > 1)
3056     {
3057         /* TREEVIEW_ITEM rechaining */
3058         INT count = 0;
3059         HTREEITEM item = 0;
3060         HTREEITEM nextItem = 0;
3061         HTREEITEM prevItem = 0;
3062 
3063         HDPA sortList = TREEVIEW_BuildChildDPA(parent);
3064 
3065         if (sortList == NULL)
3066             return FALSE;
3067 
3068         /* let DPA sort the list */
3069         DPA_Sort(sortList, pfnCompare, lpCompare);
3070 
3071         /* The order of DPA entries has been changed, so fixup the
3072          * nextSibling and prevSibling pointers. */
3073 
3074         item = DPA_GetPtr(sortList, count++);
3075         while ((nextItem = DPA_GetPtr(sortList, count++)) != NULL)
3076         {
3077             /* link the two current item together */
3078             item->nextSibling = nextItem;
3079             nextItem->prevSibling = item;
3080 
3081             if (prevItem == NULL)
3082             {
3083                 /* this is the first item, update the parent */
3084                 parent->firstChild = item;
3085                 item->prevSibling = NULL;
3086             }
3087             else
3088             {
3089                 /* fix the back chaining */
3090                 item->prevSibling = prevItem;
3091             }
3092 
3093             /* get ready for the next one */
3094             prevItem = item;
3095             item = nextItem;
3096         }
3097 
3098         /* the last item is pointed to by item and never has a sibling */
3099         item->nextSibling = NULL;
3100         parent->lastChild = item;
3101 
3102         DPA_Destroy(sortList);
3103 
3104         TREEVIEW_VerifyTree(infoPtr);
3105 
3106         if (parent->state & TVIS_EXPANDED)
3107         {
3108             int visOrder = infoPtr->firstVisible->visibleOrder;
3109 
3110         if (parent == infoPtr->root)
3111             TREEVIEW_RecalculateVisibleOrder(infoPtr, NULL);
3112         else
3113             TREEVIEW_RecalculateVisibleOrder(infoPtr, parent);
3114 
3115             if (TREEVIEW_IsChildOf(parent, infoPtr->firstVisible))
3116             {
3117                 TREEVIEW_ITEM *item;
3118 
3119                 for (item = infoPtr->root->firstChild; item != NULL;
3120                      item = TREEVIEW_GetNextListItem(infoPtr, item))
3121                 {
3122                     if (item->visibleOrder == visOrder)
3123                         break;
3124                 }
3125 
3126                 if (!item) item = parent->firstChild;
3127                 TREEVIEW_SetFirstVisible(infoPtr, item, FALSE);
3128             }
3129 
3130             TREEVIEW_Invalidate(infoPtr, NULL);
3131         }
3132 
3133         return TRUE;
3134     }
3135     return FALSE;
3136 }
3137 
3138 
3139 /***************************************************************************
3140  * Setup the treeview structure with regards of the sort method
3141  * and sort the children of the TV item specified in lParam
3142  */
3143 static LRESULT
3144 TREEVIEW_SortChildrenCB(TREEVIEW_INFO *infoPtr, LPTVSORTCB pSort)
3145 {
3146     return TREEVIEW_Sort(infoPtr, pSort->hParent, pSort);
3147 }
3148 
3149 
3150 /***************************************************************************
3151  * Sort the children of the TV item specified in lParam.
3152  */
3153 static LRESULT
3154 TREEVIEW_SortChildren(TREEVIEW_INFO *infoPtr, LPARAM lParam)
3155 {
3156     return TREEVIEW_Sort(infoPtr, (HTREEITEM)lParam, NULL);
3157 }
3158 
3159 
3160 /* Expansion/Collapse ***************************************************/
3161 
3162 static BOOL
3163 TREEVIEW_SendExpanding(const TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *wineItem,
3164                        UINT action)
3165 {
3166     return !TREEVIEW_SendTreeviewNotify(infoPtr, TVN_ITEMEXPANDINGW, action,
3167                                         TVIF_HANDLE | TVIF_STATE | TVIF_PARAM
3168                                         | TVIF_IMAGE | TVIF_SELECTEDIMAGE,
3169                                         0, wineItem);
3170 }
3171 
3172 static VOID
3173 TREEVIEW_SendExpanded(const TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *wineItem,
3174                       UINT action)
3175 {
3176     TREEVIEW_SendTreeviewNotify(infoPtr, TVN_ITEMEXPANDEDW, action,
3177                                 TVIF_HANDLE | TVIF_STATE | TVIF_PARAM
3178                                 | TVIF_IMAGE | TVIF_SELECTEDIMAGE,
3179                                 0, wineItem);
3180 }
3181 
3182 
3183 /* This corresponds to TVM_EXPAND with TVE_COLLAPSE.
3184  * bRemoveChildren corresponds to TVE_COLLAPSERESET. */
3185 static BOOL
3186 TREEVIEW_Collapse(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *wineItem,
3187                   BOOL bRemoveChildren, BOOL bUser)
3188 {
3189     UINT action = TVE_COLLAPSE | (bRemoveChildren ? TVE_COLLAPSERESET : 0);
3190     BOOL bSetSelection, bSetFirstVisible;
3191     RECT scrollRect;
3192     LONG scrollDist = 0;
3193     TREEVIEW_ITEM *nextItem = NULL, *tmpItem;
3194 
3195     TRACE("TVE_COLLAPSE %p %s\n", wineItem, TREEVIEW_ItemName(wineItem));
3196 
3197     if (!(wineItem->state & TVIS_EXPANDED))
3198         return FALSE;
3199 
3200     if (bUser || !(wineItem->state & TVIS_EXPANDEDONCE))
3201         TREEVIEW_SendExpanding(infoPtr, wineItem, action);
3202 
3203     if (wineItem->firstChild == NULL)
3204         return FALSE;
3205 
3206     wineItem->state &= ~TVIS_EXPANDED;
3207 
3208     if (bUser || !(wineItem->state & TVIS_EXPANDEDONCE))
3209         TREEVIEW_SendExpanded(infoPtr, wineItem, action);
3210 
3211     bSetSelection = (infoPtr->selectedItem != NULL
3212                      && TREEVIEW_IsChildOf(wineItem, infoPtr->selectedItem));
3213 
3214     bSetFirstVisible = (infoPtr->firstVisible != NULL
3215                         && TREEVIEW_IsChildOf(wineItem, infoPtr->firstVisible));
3216 
3217     tmpItem = wineItem;
3218     while (tmpItem)
3219     {
3220         if (tmpItem->nextSibling)
3221         {
3222             nextItem = tmpItem->nextSibling;
3223             break;
3224         }
3225         tmpItem = tmpItem->parent;
3226     }
3227 
3228     if (nextItem)
3229         scrollDist = nextItem->rect.top;
3230 
3231     if (bRemoveChildren)
3232     {
3233         INT old_cChildren = wineItem->cChildren;
3234         TRACE("TVE_COLLAPSERESET\n");
3235         wineItem->state &= ~TVIS_EXPANDEDONCE;
3236         TREEVIEW_RemoveAllChildren(infoPtr, wineItem);
3237         wineItem->cChildren = old_cChildren;
3238     }
3239 
3240     if (wineItem->firstChild)
3241     {
3242         TREEVIEW_ITEM *item, *sibling;
3243 
3244         sibling = TREEVIEW_GetNextListItem(infoPtr, wineItem);
3245 
3246         for (item = wineItem->firstChild; item != sibling;
3247              item = TREEVIEW_GetNextListItem(infoPtr, item))
3248         {
3249             item->visibleOrder = -1;
3250         }
3251     }
3252 
3253     TREEVIEW_RecalculateVisibleOrder(infoPtr, wineItem);
3254 
3255     if (nextItem)
3256         scrollDist = -(scrollDist - nextItem->rect.top);
3257 
3258     if (bSetSelection)
3259     {
3260         /* Don't call DoSelectItem, it sends notifications. */
3261         if (TREEVIEW_ValidItem(infoPtr, infoPtr->selectedItem))
3262             infoPtr->selectedItem->state &= ~TVIS_SELECTED;
3263         wineItem->state |= TVIS_SELECTED;
3264         infoPtr->selectedItem = wineItem;
3265     }
3266 
3267     TREEVIEW_UpdateScrollBars(infoPtr);
3268 
3269     scrollRect.left = 0;
3270     scrollRect.right = infoPtr->clientWidth;
3271     scrollRect.bottom = infoPtr->clientHeight;
3272 
3273     if (nextItem)
3274     {
3275         scrollRect.top = nextItem->rect.top;
3276 
3277         ScrollWindowEx (infoPtr->hwnd, 0, scrollDist, &scrollRect, &scrollRect,
3278                        NULL, NULL, SW_ERASE | SW_INVALIDATE);
3279         TREEVIEW_Invalidate(infoPtr, wineItem);
3280     } else {
3281         scrollRect.top = wineItem->rect.top;
3282         InvalidateRect(infoPtr->hwnd, &scrollRect, TRUE);
3283     }
3284 
3285     TREEVIEW_SetFirstVisible(infoPtr,
3286                              bSetFirstVisible ? wineItem : infoPtr->firstVisible,
3287                              TRUE);
3288 
3289     return TRUE;
3290 }
3291 
3292 static BOOL
3293 TREEVIEW_Expand(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *wineItem,
3294                 BOOL bExpandPartial, BOOL bUser)
3295 {
3296     LONG scrollDist;
3297     LONG orgNextTop = 0;
3298     RECT scrollRect;
3299     TREEVIEW_ITEM *nextItem, *tmpItem;
3300 
3301     TRACE("\n");
3302 
3303     if (wineItem->state & TVIS_EXPANDED)
3304        return TRUE;
3305 
3306     tmpItem = wineItem; nextItem = NULL;
3307     while (tmpItem)
3308     {
3309         if (tmpItem->nextSibling)
3310         {
3311             nextItem = tmpItem->nextSibling;
3312             break;
3313         }
3314         tmpItem = tmpItem->parent;
3315     }
3316 
3317     if (nextItem)
3318         orgNextTop = nextItem->rect.top;
3319 
3320     TRACE("TVE_EXPAND %p %s\n", wineItem, TREEVIEW_ItemName(wineItem));
3321 
3322     if (bUser || ((wineItem->cChildren != 0) &&
3323                   !(wineItem->state & TVIS_EXPANDEDONCE)))
3324     {
3325         if (!TREEVIEW_SendExpanding(infoPtr, wineItem, TVE_EXPAND))
3326         {
3327             TRACE("  TVN_ITEMEXPANDING returned TRUE, exiting...\n");
3328             return FALSE;
3329         }
3330 
3331         if (!wineItem->firstChild)
3332             return FALSE;
3333 
3334         wineItem->state |= TVIS_EXPANDED;
3335         TREEVIEW_SendExpanded(infoPtr, wineItem, TVE_EXPAND);
3336         wineItem->state |= TVIS_EXPANDEDONCE;
3337     }
3338     else
3339     {
3340         if (!wineItem->firstChild)
3341             return FALSE;
3342 
3343         /* this item has already been expanded */
3344         wineItem->state |= TVIS_EXPANDED;
3345     }
3346 
3347     if (bExpandPartial)
3348         FIXME("TVE_EXPANDPARTIAL not implemented\n");
3349 
3350     if (ISVISIBLE(wineItem))
3351     {
3352         TREEVIEW_RecalculateVisibleOrder(infoPtr, wineItem);
3353         TREEVIEW_UpdateSubTree(infoPtr, wineItem);
3354         TREEVIEW_UpdateScrollBars(infoPtr);
3355 
3356         scrollRect.left = 0;
3357         scrollRect.bottom = infoPtr->treeHeight;
3358         scrollRect.right = infoPtr->clientWidth;
3359         if (nextItem)
3360         {
3361             scrollDist = nextItem->rect.top - orgNextTop;
3362             scrollRect.top = orgNextTop;
3363 
3364             ScrollWindowEx (infoPtr->hwnd, 0, scrollDist, &scrollRect, NULL,
3365                         NULL, NULL, SW_ERASE | SW_INVALIDATE);
3366             TREEVIEW_Invalidate (infoPtr, wineItem);
3367         } else {
3368             scrollRect.top = wineItem->rect.top;
3369             InvalidateRect(infoPtr->hwnd, &scrollRect, FALSE);
3370         }
3371 
3372         /* Scroll up so that as many children as possible are visible.
3373         * This fails when expanding causes an HScroll bar to appear, but we
3374         * don't know that yet, so the last item is obscured. */
3375         if (wineItem->firstChild != NULL)
3376         {
3377             int nChildren = wineItem->lastChild->visibleOrder
3378                 - wineItem->firstChild->visibleOrder + 1;
3379 
3380             int visible_pos = wineItem->visibleOrder
3381                 - infoPtr->firstVisible->visibleOrder;
3382 
3383             int rows_below = TREEVIEW_GetVisibleCount(infoPtr) - visible_pos - 1;
3384 
3385             if (visible_pos > 0 && nChildren > rows_below)
3386             {
3387                 int scroll = nChildren - rows_below;
3388 
3389                 if (scroll > visible_pos)
3390                     scroll = visible_pos;
3391 
3392                 if (scroll > 0)
3393                 {
3394                     TREEVIEW_ITEM *newFirstVisible
3395                         = TREEVIEW_GetListItem(infoPtr, infoPtr->firstVisible,
3396                                             scroll);
3397 
3398 
3399                     TREEVIEW_SetFirstVisible(infoPtr, newFirstVisible, TRUE);
3400                 }
3401             }
3402         }
3403     }
3404 
3405     return TRUE;
3406 }
3407 
3408 static BOOL
3409 TREEVIEW_Toggle(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *wineItem, BOOL bUser)
3410 {
3411     TRACE("\n");
3412 
3413     if (wineItem->state & TVIS_EXPANDED)
3414         return TREEVIEW_Collapse(infoPtr, wineItem, FALSE, bUser);
3415     else
3416         return TREEVIEW_Expand(infoPtr, wineItem, FALSE, bUser);
3417 }
3418 
3419 static VOID
3420 TREEVIEW_ExpandAll(TREEVIEW_INFO *infoPtr, TREEVIEW_ITEM *item)
3421 {
3422     TREEVIEW_Expand(infoPtr, item, FALSE, TRUE);
3423 
3424     for (item = item->firstChild; item != NULL; item = item->nextSibling)
3425     {
3426         if (TREEVIEW_HasChildren(infoPtr, item))
3427             TREEVIEW_ExpandAll(infoPtr, item);
3428     }
3429 }
3430 
3431 /* Note:If the specified item is the child of a collapsed parent item,
3432    the parent's list of child items is (recursively) expanded to reveal the
3433    specified item. This is mentioned for TREEVIEW_SelectItem; don't
3434    know if it also applies here.
3435 */
3436 
3437 static LRESULT
3438 TREEVIEW_ExpandMsg(TREEVIEW_INFO *infoPtr, UINT flag, HTREEITEM wineItem)
3439 {
3440     if (!TREEVIEW_ValidItem(infoPtr, wineItem))
3441         return 0;
3442 
3443     TRACE("For (%s) item:%d, flags %x, state:%d\n",
3444               TREEVIEW_ItemName(wineItem), flag,
3445               TREEVIEW_GetItemIndex(infoPtr, wineItem), wineItem->state);
3446 
3447     switch (flag & TVE_TOGGLE)
3448     {
3449     case TVE_COLLAPSE:
3450         return TREEVIEW_Collapse(infoPtr, wineItem, flag & TVE_COLLAPSERESET,
3451                                  FALSE);
3452 
3453     case TVE_EXPAND:
3454         return TREEVIEW_Expand(infoPtr, wineItem, flag & TVE_EXPANDPARTIAL,
3455                                FALSE);
3456 
3457     case TVE_TOGGLE:
3458         return TREEVIEW_Toggle(infoPtr, wineItem, TRUE);
3459 
3460     default:
3461         return 0;
3462     }
3463 
3464 #if 0
3465     TRACE("Exiting, Item %p state is now %d...\n", wineItem, wineItem->state);
3466 #endif
3467 }
3468 
3469 /* Hit-Testing **********************************************************/
3470 
3471 static TREEVIEW_ITEM *
3472 TREEVIEW_HitTestPoint(const TREEVIEW_INFO *infoPtr, POINT pt)
3473 {
3474     TREEVIEW_ITEM *wineItem;
3475     LONG row;
3476 
3477     if (!infoPtr->firstVisible)
3478         return NULL;
3479 
3480     row = pt.y / infoPtr->uItemHeight + infoPtr->firstVisible->visibleOrder;
3481 
3482     for (wineItem = infoPtr->firstVisible; wineItem != NULL;
3483          wineItem = TREEVIEW_GetNextListItem(infoPtr, wineItem))
3484     {
3485         if (row >= wineItem->visibleOrder
3486             && row < wineItem->visibleOrder + wineItem->iIntegral)
3487             break;
3488     }
3489 
3490     return wineItem;
3491 }
3492 
3493 static LRESULT
3494 TREEVIEW_HitTest(const TREEVIEW_INFO *infoPtr, LPTVHITTESTINFO lpht)
3495 {
3496     TREEVIEW_ITEM *wineItem;
3497     RECT rect;
3498     UINT status;
3499     LONG x, y;
3500 
3501     lpht->hItem = 0;
3502     GetClientRect(infoPtr->hwnd, &rect);
3503     status = 0;
3504     x = lpht->pt.x;
3505     y = lpht->pt.y;
3506 
3507     if (x < rect.left)
3508     {
3509         status |= TVHT_TOLEFT;
3510     }
3511     else if (x > rect.right)
3512     {
3513         status |= TVHT_TORIGHT;
3514     }
3515 
3516     if (y < rect.top)
3517     {
3518         status |= TVHT_ABOVE;
3519     }
3520     else if (y > rect.bottom)
3521     {
3522         status |= TVHT_BELOW;
3523     }
3524 
3525     if (status)
3526     {
3527         lpht->flags = status;
3528         return 0;
3529     }
3530 
3531     wineItem = TREEVIEW_HitTestPoint(infoPtr, lpht->pt);
3532     if (!wineItem)
3533     {
3534         lpht->flags = TVHT_NOWHERE;
3535         return 0;
3536     }
3537 
3538     if (x >= wineItem->textOffset + wineItem->textWidth)
3539     {
3540         lpht->flags = TVHT_ONITEMRIGHT;
3541     }
3542     else if (x >= wineItem->textOffset)
3543     {
3544         lpht->flags = TVHT_ONITEMLABEL;
3545     }
3546     else if (x >= wineItem->imageOffset)
3547     {
3548         lpht->flags = TVHT_ONITEMICON;
3549     }
3550     else if (x >= wineItem->stateOffset)
3551     {
3552         lpht->flags = TVHT_ONITEMSTATEICON;
3553     }
3554     else if (x >= wineItem->linesOffset && infoPtr->dwStyle & TVS_HASBUTTONS)
3555     {
3556         lpht->flags = TVHT_ONITEMBUTTON;
3557     }
3558     else
3559     {
3560         lpht->flags = TVHT_ONITEMINDENT;
3561     }
3562 
3563     lpht->hItem = wineItem;
3564     TRACE("(%d,%d):result %x\n", lpht->pt.x, lpht->pt.y, lpht->flags);
3565 
3566     return (LRESULT)wineItem;
3567 }
3568 
3569 /* Item Label Editing ***************************************************/
3570 
3571 static LRESULT
3572 TREEVIEW_GetEditControl(const TREEVIEW_INFO *infoPtr)
3573 {
3574     return (LRESULT)infoPtr->hwndEdit;
3575 }
3576 
3577 static LRESULT CALLBACK
3578 TREEVIEW_Edit_SubclassProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
3579 {
3580     TREEVIEW_INFO *infoPtr = TREEVIEW_GetInfoPtr(GetParent(hwnd));
3581     BOOL bCancel = FALSE;
3582     LRESULT rc;
3583 
3584     switch (uMsg)
3585     {
3586     case WM_PAINT:
3587          TRACE("WM_PAINT start\n");
3588          rc = CallWindowProcW(infoPtr->wpEditOrig, hwnd, uMsg, wParam,
3589                                  lParam);
3590          TRACE("WM_PAINT done\n");
3591          return rc;
3592 
3593     case WM_KILLFOCUS:
3594         if (infoPtr->bIgnoreEditKillFocus)
3595             return TRUE;
3596         break;
3597 
3598     case WM_DESTROY:
3599     {
3600         WNDPROC editProc = infoPtr->wpEditOrig;
3601         infoPtr->wpEditOrig = 0;
3602         SetWindowLongPtrW(hwnd, GWLP_WNDPROC, (DWORD_PTR)editProc);
3603         return CallWindowProcW(editProc, hwnd, uMsg, wParam, lParam);
3604     }
3605 
3606     case WM_GETDLGCODE:
3607         return DLGC_WANTARROWS | DLGC_WANTALLKEYS;
3608 
3609     case WM_KEYDOWN:
3610        if (wParam == VK_ESCAPE)
3611         {
3612             bCancel = TRUE;
3613             break;
3614         }
3615        else if (wParam == VK_RETURN)
3616         {
3617             break;
3618         }
3619 
3620         /* fall through */
3621     default:
3622         return CallWindowProcW(infoPtr->wpEditOrig, hwnd, uMsg, wParam, lParam);
3623     }
3624 
3625     /* Processing TVN_ENDLABELEDIT message could kill the focus       */
3626     /* eg. Using a messagebox                                         */
3627 
3628     infoPtr->bIgnoreEditKillFocus = TRUE;
3629     TREEVIEW_EndEditLabelNow(infoPtr, bCancel || !infoPtr->bLabelChanged);
3630     infoPtr->bIgnoreEditKillFocus = FALSE;
3631 
3632     return 0;
3633 }
3634 
3635 
3636 /* should handle edit control messages here */
3637 
3638 static LRESULT
3639 TREEVIEW_Command(TREEVIEW_INFO *infoPtr, WPARAM wParam, LPARAM lParam)
3640 {
3641     TRACE("code=%x, id=%x, handle=%lx\n", HIWORD(wParam), LOWORD(wParam), lParam);
3642 
3643     switch (HIWORD(wParam))
3644     {
3645     case EN_UPDATE:
3646         {
3647             /*
3648              * Adjust the edit window size
3649              */
3650             WCHAR buffer[1024];
3651             TREEVIEW_ITEM *editItem = infoPtr->editItem;
3652             HDC hdc = GetDC(infoPtr->hwndEdit);
3653             SIZE sz;
3654             HFONT hFont, hOldFont = 0;
3655 
3656             TRACE("edit=%p\n", infoPtr->hwndEdit);
3657 
3658             if (!IsWindow(infoPtr->hwndEdit) || !hdc) return FALSE;
3659 
3660             infoPtr->bLabelChanged = TRUE;
3661 
3662             GetWindowTextW(infoPtr->hwndEdit, buffer, sizeof(buffer)/sizeof(buffer[0]));
3663 
3664             /* Select font to get the right dimension of the string */
3665             hFont = (HFONT)SendMessageW(infoPtr->hwndEdit, WM_GETFONT, 0, 0);
3666 
3667             if (hFont != 0)
3668             {
3669                 hOldFont = SelectObject(hdc, hFont);
3670             }
3671 
3672             if (GetTextExtentPoint32W(hdc, buffer, strlenW(buffer), &sz))
3673             {
3674                 TEXTMETRICW textMetric;
3675 
3676                 /* Add Extra spacing for the next character */
3677                 GetTextMetricsW(hdc, &textMetric);
3678                 sz.cx += (textMetric.tmMaxCharWidth * 2);
3679 
3680                 sz.cx = max(sz.cx, textMetric.tmMaxCharWidth * 3);
3681                 sz.cx = min(sz.cx,
3682                             infoPtr->clientWidth - editItem->textOffset + 2);
3683 
3684                 SetWindowPos(infoPtr->hwndEdit,
3685                              HWND_TOP,
3686                              0,
3687                              0,
3688                              sz.cx,
3689                              editItem->rect.bottom - editItem->rect.top + 3,
3690                              SWP_NOMOVE | SWP_DRAWFRAME);
3691             }
3692 
3693             if (hFont != 0)
3694             {
3695                 SelectObject(hdc, hOldFont);
3696             }
3697 
3698             ReleaseDC(infoPtr->hwnd, hdc);
3699             break;
3700         }
3701     case EN_KILLFOCUS:
3702         /* apparently we should respect passed handle value */
3703         if (infoPtr->hwndEdit != (HWND)lParam) return FALSE;
3704 
3705         TREEVIEW_EndEditLabelNow(infoPtr, FALSE);
3706         break;
3707 
3708     default:
3709         return SendMessageW(infoPtr->hwndNotify, WM_COMMAND, wParam, lParam);
3710     }
3711 
3712     return 0;
3713 }
3714 
3715 static HWND
3716 TREEVIEW_EditLabel(TREEVIEW_INFO *infoPtr, HTREEITEM hItem)
3717 {
3718     HWND hwnd = infoPtr->hwnd;
3719     HWND hwndEdit;
3720     SIZE sz;
3721     HINSTANCE hinst = (HINSTANCE)GetWindowLongPtrW(hwnd, GWLP_HINSTANCE);
3722     HDC hdc;
3723     HFONT hOldFont=0;
3724     TEXTMETRICW textMetric;
3725 
3726     TRACE("%p %p\n", hwnd, hItem);
3727     if (!TREEVIEW_ValidItem(infoPtr, hItem))
3728         return NULL;
3729 
3730     if (infoPtr->hwndEdit)
3731         return infoPtr->hwndEdit;
3732 
3733     infoPtr->bLabelChanged = FALSE;
3734 
3735     /* make edit item visible */
3736     TREEVIEW_EnsureVisible(infoPtr, hItem, TRUE);
3737 
3738     TREEVIEW_UpdateDispInfo(infoPtr, hItem, TVIF_TEXT);
3739 
3740     hdc = GetDC(hwnd);
3741     /* Select the font to get appropriate metric dimensions */
3742     if (infoPtr->hFont != 0)
3743     {
3744         hOldFont = SelectObject(hdc, infoPtr->hFont);
3745     }
3746 
3747     /* Get string length in pixels */
3748     if (hItem->pszText)
3749         GetTextExtentPoint32W(hdc, hItem->pszText, strlenW(hItem->pszText),
3750                         &sz);
3751     else
3752         GetTextExtentPoint32A(hdc, "", 0, &sz);
3753 
3754     /* Add Extra spacing for the next character */
3755     GetTextMetricsW(hdc, &textMetric);
3756     sz.cx += (textMetric.tmMaxCharWidth * 2);
3757 
3758     sz.cx = max(sz.cx, textMetric.tmMaxCharWidth * 3);
3759     sz.cx = min(sz.cx, infoPtr->clientWidth - hItem->textOffset + 2);
3760 
3761     if (infoPtr->hFont != 0)
3762     {
3763         SelectObject(hdc, hOldFont);
3764     }
3765 
3766     ReleaseDC(hwnd, hdc);
3767 
3768     infoPtr->editItem = hItem;
3769 
3770     hwndEdit = CreateWindowExW(WS_EX_LEFT,
3771                                WC_EDITW,
3772                                0,
3773                                WS_CHILD | WS_BORDER | ES_AUTOHSCROLL |
3774                                WS_CLIPSIBLINGS | ES_WANTRETURN |
3775                                ES_LEFT, hItem->textOffset - 2,
3776                                hItem->rect.top - 1, sz.cx + 3,
3777                                hItem->rect.bottom -
3778                                hItem->rect.top + 3, hwnd, 0, hinst, 0);
3779 /* FIXME: (HMENU)IDTVEDIT,pcs->hInstance,0); */
3780 
3781     infoPtr->hwndEdit = hwndEdit;
3782 
3783     /* Get a 2D border. */
3784     SetWindowLongW(hwndEdit, GWL_EXSTYLE,
3785                    GetWindowLongW(hwndEdit, GWL_EXSTYLE) & ~WS_EX_CLIENTEDGE);
3786     SetWindowLongW(hwndEdit, GWL_STYLE,
3787                    GetWindowLongW(hwndEdit, GWL_STYLE) | WS_BORDER);
3788 
3789     SendMessageW(hwndEdit, WM_SETFONT,
3790                  (WPARAM)TREEVIEW_FontForItem(infoPtr, hItem), FALSE);
3791 
3792     infoPtr->wpEditOrig = (WNDPROC)SetWindowLongPtrW(hwndEdit, GWLP_WNDPROC,
3793                                                   (DWORD_PTR)
3794                                                   TREEVIEW_Edit_SubclassProc);
3795 
3796     if (TREEVIEW_BeginLabelEditNotify(infoPtr, hItem))
3797     {
3798         DestroyWindow(hwndEdit);
3799         infoPtr->hwndEdit = 0;
3800         infoPtr->editItem = NULL;
3801         return NULL;
3802     }
3803 
3804     if (hItem->pszText)
3805         SetWindowTextW(hwndEdit, hItem->pszText);
3806 
3807     SetFocus(hwndEdit);
3808     SendMessageW(hwndEdit, EM_SETSEL, 0, -1);
3809     ShowWindow(hwndEdit, SW_SHOW);
3810 
3811     return hwndEdit;
3812 }
3813 
3814 
3815 static LRESULT
3816 TREEVIEW_EndEditLabelNow(TREEVIEW_INFO *infoPtr, BOOL bCancel)
3817 {
3818     HWND hwnd = infoPtr->hwnd;
3819     TREEVIEW_ITEM *editedItem = infoPtr->editItem;
3820     NMTVDISPINFOW tvdi;
3821     BOOL bCommit;
3822     WCHAR tmpText[1024] = { '\0' };
3823     WCHAR *newText = tmpText;
3824     int iLength = 0;
3825 
3826     if (!IsWindow(infoPtr->hwndEdit)) return FALSE;
3827 
3828     tvdi.hdr.hwndFrom = hwnd;
3829     tvdi.hdr.idFrom = GetWindowLongPtrW(hwnd, GWLP_ID);
3830     tvdi.hdr.code = get_notifycode(infoPtr, TVN_ENDLABELEDITW);
3831     tvdi.item.mask = 0;
3832     tvdi.item.hItem = editedItem;
3833     tvdi.item.state = editedItem->state;
3834     tvdi.item.lParam = editedItem->lParam;
3835 
3836     if (!bCancel)
3837     {
3838         if (!infoPtr->bNtfUnicode)
3839             iLength = GetWindowTextA(infoPtr->hwndEdit, (LPSTR)tmpText, 1023);
3840         else
3841             iLength = GetWindowTextW(infoPtr->hwndEdit, tmpText, 1023);
3842 
3843         if (iLength >= 1023)
3844         {
3845             ERR("Insufficient space to retrieve new item label\n");
3846         }
3847 
3848         tvdi.item.mask = TVIF_TEXT;
3849         tvdi.item.pszText = tmpText;
3850         tvdi.item.cchTextMax = iLength + 1;
3851     }
3852     else
3853     {
3854         tvdi.item.pszText = NULL;
3855         tvdi.item.cchTextMax = 0;
3856     }
3857 
3858     bCommit = (BOOL)TREEVIEW_SendRealNotify(infoPtr, tvdi.hdr.idFrom, (LPARAM)&tvdi);
3859 
3860     if (!bCancel && bCommit)    /* Apply the changes */
3861     {
3862         if (!infoPtr->bNtfUnicode)
3863         {
3864             DWORD len = MultiByteToWideChar( CP_ACP, 0, (LPSTR)tmpText, -1, NULL, 0 );
3865             newText = Alloc(len * sizeof(WCHAR));
3866             MultiByteToWideChar( CP_ACP, 0, (LPSTR)tmpText, -1, newText, len );
3867             iLength = len - 1;
3868         }
3869 
3870         if (strcmpW(newText, editedItem->pszText) != 0)
3871         {
3872             WCHAR *ptr = ReAlloc(editedItem->pszText, sizeof(WCHAR)*(iLength + 1));
3873             if (ptr == NULL)
3874             {
3875                 ERR("OutOfMemory, cannot allocate space for label\n");
3876                 if(newText != tmpText) Free(newText);
3877                 DestroyWindow(infoPtr->hwndEdit);
3878                 infoPtr->hwndEdit = 0;
3879                 infoPtr->editItem = NULL;
3880                 return FALSE;
3881             }
3882             else
3883             {
3884                 editedItem->pszText = ptr;
3885                 editedItem->cchTextMax = iLength + 1;
3886                 strcpyW(editedItem->pszText, newText);
3887                 TREEVIEW_ComputeTextWidth(infoPtr, editedItem, 0);
3888             }
3889         }
3890         if(newText != tmpText) Free(newText);
3891     }
3892 
3893     ShowWindow(infoPtr->hwndEdit, SW_HIDE);
3894     DestroyWindow(infoPtr->hwndEdit);
3895     infoPtr->hwndEdit = 0;
3896     infoPtr->editItem = NULL;
3897     return TRUE;
3898 }
3899 
3900 static LRESULT
3901 TREEVIEW_HandleTimer(TREEVIEW_INFO *infoPtr, WPARAM wParam)
3902 {
3903     if (wParam != TV_EDIT_TIMER)
3904     {
3905         ERR("got unknown timer\n");
3906         return 1;
3907     }
3908 
3909     KillTimer(infoPtr->hwnd, TV_EDIT_TIMER);
3910     infoPtr->Timer &= ~TV_EDIT_TIMER_SET;
3911 
3912     TREEVIEW_EditLabel(infoPtr, infoPtr->selectedItem);
3913 
3914     return 0;
3915 }
3916 
3917 
3918 /* Mouse Tracking/Drag **************************************************/
3919 
3920 /***************************************************************************
3921  * This is quite unusual piece of code, but that's how it's implemented in
3922  * Windows.
3923  */
3924 static LRESULT
3925 TREEVIEW_TrackMouse(const TREEVIEW_INFO *infoPtr, POINT pt)
3926 {
3927     INT cxDrag = GetSystemMetrics(SM_CXDRAG);
3928     INT cyDrag = GetSystemMetrics(SM_CYDRAG);
3929     RECT r;
3930     MSG msg;
3931 
3932     r.top = pt.y - cyDrag;
3933     r.left = pt.x - cxDrag;
3934     r.bottom = pt.y + cyDrag;
3935     r.right = pt.x + cxDrag;
3936 
3937     SetCapture(infoPtr->hwnd);
3938 
3939     while (1)
3940     {
3941         if (PeekMessageW(&msg, 0, 0, 0, PM_REMOVE | PM_NOYIELD))
3942         {
3943             if (msg.message == WM_MOUSEMOVE)
3944             {
3945                 pt.x = (short)LOWORD(msg.lParam);
3946                 pt.y = (short)HIWORD(msg.lParam);
3947                 if (PtInRect(&r, pt))
3948                     continue;
3949                 else
3950                 {
3951                     ReleaseCapture();
3952                     return 1;
3953                 }
3954             }
3955             else if (msg.message >= WM_LBUTTONDOWN &&
3956                      msg.message <= WM_RBUTTONDBLCLK)
3957             {
3958                 if (msg.message == WM_RBUTTONUP)
3959                     TREEVIEW_RButtonUp(infoPtr, &pt);
3960                 break;
3961             }
3962 
3963             DispatchMessageW(&msg);
3964         }
3965 
3966         if (GetCapture() != infoPtr->hwnd)
3967             return 0;
3968     }
3969 
3970     ReleaseCapture();
3971     return 0;
3972 }
3973 
3974 
3975 static LRESULT
3976 TREEVIEW_LButtonDoubleClick(TREEVIEW_INFO *infoPtr, LPARAM lParam)
3977 {
3978     TREEVIEW_ITEM *wineItem;
3979     TVHITTESTINFO hit;
3980 
3981     TRACE("\n");
3982     SetFocus(infoPtr->hwnd);
3983 
3984     if (infoPtr->Timer & TV_EDIT_TIMER_SET)
3985     {
3986         /* If there is pending 'edit label' event - kill it now */
3987         KillTimer(infoPtr->hwnd, TV_EDIT_TIMER);
3988     }
3989 
3990     hit.pt.x = (short)LOWORD(lParam);
3991     hit.pt.y = (short)HIWORD(lParam);
3992 
3993     wineItem = (TREEVIEW_ITEM *)TREEVIEW_HitTest(infoPtr, &hit);
3994     if (!wineItem)
3995         return 0;
3996     TRACE("item %d\n", TREEVIEW_GetItemIndex(infoPtr, wineItem));
3997 
3998     if (TREEVIEW_SendSimpleNotify(infoPtr, NM_DBLCLK) == FALSE)
3999     {                           /* FIXME! */
4000         switch (hit.flags)
4001         {
4002         case TVHT_ONITEMRIGHT:
4003             /* FIXME: we should not have sent NM_DBLCLK in this case. */
4004             break;
4005 
4006         case TVHT_ONITEMINDENT:
4007             if (!(infoPtr->dwStyle & TVS_HASLINES))
4008             {
4009                 break;
4010             }
4011             else
4012             {
4013                 int level = hit.pt.x / infoPtr->uIndent;
4014                 if (!(infoPtr->dwStyle & TVS_LINESATROOT)) level++;
4015 
4016                 while (wineItem->iLevel > level)
4017                 {
4018                     wineItem = wineItem->parent;
4019                 }
4020 
4021                 /* fall through */
4022             }
4023 
4024         case TVHT_ONITEMLABEL:
4025         case TVHT_ONITEMICON:
4026         case TVHT_ONITEMBUTTON:
4027             TREEVIEW_Toggle(infoPtr, wineItem, TRUE);
4028             break;
4029 
4030         case TVHT_ONITEMSTATEICON:
4031            if (infoPtr->dwStyle & TVS_CHECKBOXES)
4032                TREEVIEW_ToggleItemState(infoPtr, wineItem);
4033            else
4034                TREEVIEW_Toggle(infoPtr, wineItem, TRUE);
4035            break;
4036         }
4037     }
4038     return TRUE;
4039 }
4040 
4041 
4042 static LRESULT
4043 TREEVIEW_LButtonDown(TREEVIEW_INFO *infoPtr, LPARAM lParam)
4044 {
4045     HWND hwnd = infoPtr->hwnd;
4046     TVHITTESTINFO ht;
4047     BOOL bTrack, bDoLabelEdit;
4048 
4049     /* If Edit control is active - kill it and return.
4050      * The best way to do it is to set focus to itself.
4051      * Edit control subclassed procedure will automatically call
4052      * EndEditLabelNow.
4053      */
4054     if (infoPtr->hwndEdit)
4055     {
4056         SetFocus(hwnd);
4057         return 0;
4058     }
4059 
4060     ht.pt.x = (short)LOWORD(lParam);
4061     ht.pt.y = (short)HIWORD(lParam);
4062 
4063     TREEVIEW_HitTest(infoPtr, &ht);
4064     TRACE("item %d\n", TREEVIEW_GetItemIndex(infoPtr, ht.hItem));
4065 
4066     /* update focusedItem and redraw both items */
4067     if(ht.hItem && (ht.flags & TVHT_ONITEM))
4068     {
4069         infoPtr->focusedItem = ht.hItem;
4070         TREEVIEW_InvalidateItem(infoPtr, infoPtr->focusedItem);
4071         TREEVIEW_InvalidateItem(infoPtr, infoPtr->selectedItem);
4072     }
4073 
4074     bTrack = (ht.flags & TVHT_ONITEM)
4075         && !(infoPtr->dwStyle & TVS_DISABLEDRAGDROP);
4076 
4077     /*
4078      * If the style allows editing and the node is already selected
4079      * and the click occurred on the item label...
4080      */
4081     bDoLabelEdit = (infoPtr->dwStyle & TVS_EDITLABELS) &&
4082         (ht.flags & TVHT_ONITEMLABEL) && (infoPtr->selectedItem == ht.hItem);
4083 
4084     /* Send NM_CLICK right away */
4085     if (!bTrack)
4086         if (TREEVIEW_SendSimpleNotify(infoPtr, NM_CLICK))
4087             goto setfocus;
4088 
4089     if (ht.flags & TVHT_ONITEMBUTTON)
4090     {
4091         TREEVIEW_Toggle(infoPtr, ht.hItem, TRUE);
4092         goto setfocus;
4093     }
4094     else if (bTrack)
4095     {   /* if TREEVIEW_TrackMouse == 1 dragging occurred and the cursor left the dragged item's rectangle */
4096         if (TREEVIEW_TrackMouse(infoPtr, ht.pt))
4097         {
4098             TREEVIEW_SendTreeviewDnDNotify(infoPtr, TVN_BEGINDRAGW, ht.hItem, ht.pt);
4099             infoPtr->dropItem = ht.hItem;
4100 
4101             /* clean up focusedItem as we dragged and won't select this item */
4102             if(infoPtr->focusedItem)
4103             {
4104                 /* refresh the item that was focused */
4105                 TREEVIEW_InvalidateItem(infoPtr, infoPtr->focusedItem);
4106                 infoPtr->focusedItem = NULL;
4107 
4108                 /* refresh the selected item to return the filled background */
4109                 TREEVIEW_InvalidateItem(infoPtr, infoPtr->selectedItem);
4110             }
4111 
4112             return 0;
4113         }
4114     }
4115 
4116     if (bTrack && TREEVIEW_SendSimpleNotify(infoPtr, NM_CLICK))
4117         goto setfocus;
4118 
4119     if (bDoLabelEdit)
4120     {
4121         if (infoPtr->Timer & TV_EDIT_TIMER_SET)
4122             KillTimer(hwnd, TV_EDIT_TIMER);
4123 
4124         SetTimer(hwnd, TV_EDIT_TIMER, GetDoubleClickTime(), 0);
4125         infoPtr->Timer |= TV_EDIT_TIMER_SET;
4126     }
4127     else if (ht.flags & (TVHT_ONITEMICON|TVHT_ONITEMLABEL)) /* select the item if the hit was inside of the icon or text */
4128     {
4129         /*
4130          * if we are TVS_SINGLEEXPAND then we want this single click to
4131          * do a bunch of things.
4132          */
4133         if((infoPtr->dwStyle & TVS_SINGLEEXPAND) &&
4134           (infoPtr->hwndEdit == 0))
4135         {
4136             TREEVIEW_ITEM *SelItem;
4137 
4138             /*
4139              * Send the notification
4140              */
4141             TREEVIEW_SendTreeviewNotify(infoPtr, TVN_SINGLEEXPAND, TVC_UNKNOWN, TVIF_HANDLE | TVIF_PARAM, ht.hItem, 0);
4142 
4143             /*
4144              * Close the previous selection all the way to the root
4145              * as long as the new selection is not a child
4146              */
4147             if((infoPtr->selectedItem)
4148                 && (infoPtr->selectedItem != ht.hItem))
4149             {
4150                 BOOL closeit = TRUE;
4151                 SelItem = ht.hItem;
4152 
4153                 /* determine if the hitItem is a child of the currently selected item */
4154                 while(closeit && SelItem && TREEVIEW_ValidItem(infoPtr, SelItem) && (SelItem != infoPtr->root))
4155                 {
4156                     closeit = (SelItem != infoPtr->selectedItem);
4157                     SelItem = SelItem->parent;
4158                 }
4159 
4160                 if(closeit)
4161                 {
4162                     if(TREEVIEW_ValidItem(infoPtr, infoPtr->selectedItem))
4163                         SelItem = infoPtr->selectedItem;
4164 
4165                     while(SelItem && (SelItem != ht.hItem) && TREEVIEW_ValidItem(infoPtr, SelItem) && (SelItem != infoPtr->root))
4166                     {
4167                         TREEVIEW_Collapse(infoPtr, SelItem, FALSE, FALSE);
4168                         SelItem = SelItem->parent;
4169                     }
4170                 }
4171             }
4172 
4173             /*
4174              * Expand the current item
4175              */
4176             TREEVIEW_Expand(infoPtr, ht.hItem, TVE_TOGGLE, FALSE);
4177         }
4178 
4179         /* Select the current item */
4180         TREEVIEW_DoSelectItem(infoPtr, TVGN_CARET, ht.hItem, TVC_BYMOUSE);
4181     }
4182     else if (ht.flags & TVHT_ONITEMSTATEICON)
4183     {
4184         /* TVS_CHECKBOXES requires us to toggle the current state */
4185         if (infoPtr->dwStyle & TVS_CHECKBOXES)
4186             TREEVIEW_ToggleItemState(infoPtr, ht.hItem);
4187     }
4188 
4189   setfocus:
4190     SetFocus(hwnd);
4191     return 0;
4192 }
4193 
4194 
4195 static LRESULT
4196 TREEVIEW_RButtonDown(TREEVIEW_INFO *infoPtr, LPARAM lParam)
4197 {
4198     TVHITTESTINFO ht;
4199 
4200     if (infoPtr->hwndEdit)
4201     {
4202         SetFocus(infoPtr->hwnd);
4203         return 0;
4204     }
4205 
4206     ht.pt.x = (short)LOWORD(lParam);
4207     ht.pt.y = (short)HIWORD(lParam);
4208 
4209     TREEVIEW_HitTest(infoPtr, &ht);
4210 
4211     if (TREEVIEW_TrackMouse(infoPtr, ht.pt))
4212     {
4213         if (ht.hItem)
4214         {
4215             TREEVIEW_SendTreeviewDnDNotify(infoPtr, TVN_BEGINRDRAGW, ht.hItem, ht.pt);
4216             infoPtr->dropItem = ht.hItem;
4217         }
4218     }
4219     else
4220     {
4221         SetFocus(infoPtr->hwnd);
4222         TREEVIEW_SendSimpleNotify(infoPtr, NM_RCLICK);
4223     }
4224 
4225     return 0;
4226 }
4227 
4228 static LRESULT
4229 TREEVIEW_RButtonUp(const TREEVIEW_INFO *infoPtr, const POINT *pPt)
4230 {
4231     TVHITTESTINFO ht;
4232 
4233     ht.pt = *pPt;
4234 
4235     TREEVIEW_HitTest(infoPtr, &ht);
4236 
4237     if (ht.hItem)
4238     {
4239         /* Change to screen coordinate for WM_CONTEXTMENU */
4240         ClientToScreen(infoPtr->hwnd, &ht.pt);
4241 
4242         /* Send a WM_CONTEXTMENU message in response to the RBUTTONUP */
4243         SendMessageW(infoPtr->hwnd, WM_CONTEXTMENU,
4244             (WPARAM)infoPtr->hwnd, MAKELPARAM(ht.pt.x, ht.pt.y));
4245     }
4246     return 0;
4247 }
4248 
4249 
4250 static LRESULT
4251 TREEVIEW_CreateDragImage(TREEVIEW_INFO *infoPtr, LPARAM lParam)
4252 {
4253     TREEVIEW_ITEM *dragItem = (HTREEITEM)lParam;
4254     INT cx, cy;
4255     HDC hdc, htopdc;
4256     HWND hwtop;
4257     HBITMAP hbmp, hOldbmp;
4258     SIZE size;
4259     RECT rc;
4260     HFONT hOldFont;
4261 
4262     TRACE("\n");
4263 
4264     if (!(infoPtr->himlNormal))
4265         return 0;
4266 
4267     if (!dragItem || !TREEVIEW_ValidItem(infoPtr, dragItem))
4268         return 0;
4269 
4270     TREEVIEW_UpdateDispInfo(infoPtr, dragItem, TVIF_TEXT);
4271 
4272     hwtop = GetDesktopWindow();
4273     htopdc = GetDC(hwtop);
4274     hdc = CreateCompatibleDC(htopdc);
4275 
4276     hOldFont = SelectObject(hdc, infoPtr->hFont);
4277 
4278     if (dragItem->pszText)
4279         GetTextExtentPoint32W(hdc, dragItem->pszText, strlenW(dragItem->pszText),
4280                           &size);
4281     else
4282         GetTextExtentPoint32A(hdc, "", 0, &size);
4283 
4284     TRACE("%d %d %s\n", size.cx, size.cy, debugstr_w(dragItem->pszText));
4285     hbmp = CreateCompatibleBitmap(htopdc, size.cx, size.cy);
4286     hOldbmp = SelectObject(hdc, hbmp);
4287 
4288     ImageList_GetIconSize(infoPtr->himlNormal, &cx, &cy);
4289     size.cx += cx;
4290     if (cy > size.cy)
4291         size.cy = cy;
4292 
4293     infoPtr->dragList = ImageList_Create(size.cx, size.cy, ILC_COLOR, 10, 10);
4294     ImageList_Draw(infoPtr->himlNormal, dragItem->iImage, hdc, 0, 0,
4295                    ILD_NORMAL);
4296