xref: /reactos/dll/win32/comctl32/listview.c (revision 9393fc32)
1 /*
2  * Listview control
3  *
4  * Copyright 1998, 1999 Eric Kohl
5  * Copyright 1999 Luc Tourangeau
6  * Copyright 2000 Jason Mawdsley
7  * Copyright 2001 CodeWeavers Inc.
8  * Copyright 2002 Dimitrie O. Paun
9  * Copyright 2009-2015 Nikolay Sivov
10  * Copyright 2009 Owen Rudge for CodeWeavers
11  * Copyright 2012-2013 Daniel Jelinski
12  *
13  * This library is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU Lesser General Public
15  * License as published by the Free Software Foundation; either
16  * version 2.1 of the License, or (at your option) any later version.
17  *
18  * This library is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21  * Lesser General Public License for more details.
22  *
23  * You should have received a copy of the GNU Lesser General Public
24  * License along with this library; if not, write to the Free Software
25  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
26  *
27  * TODO:
28  *
29  * Default Message Processing
30  *   -- WM_CREATE: create the icon and small icon image lists at this point only if
31  *      the LVS_SHAREIMAGELISTS style is not specified.
32  *   -- WM_WINDOWPOSCHANGED: arrange the list items if the current view is icon
33  *      or small icon and the LVS_AUTOARRANGE style is specified.
34  *   -- WM_TIMER
35  *   -- WM_WININICHANGE
36  *
37  * Features
38  *   -- Hot item handling, mouse hovering
39  *   -- Workareas support
40  *   -- Tilemode support
41  *   -- Groups support
42  *
43  * Bugs
44  *   -- Expand large item in ICON mode when the cursor is flying over the icon or text.
45  *   -- Support CustomDraw options for _WIN32_IE >= 0x560 (see NMLVCUSTOMDRAW docs).
46  *   -- LVA_SNAPTOGRID not implemented
47  *   -- LISTVIEW_ApproximateViewRect partially implemented
48  *   -- LISTVIEW_StyleChanged doesn't handle some changes too well
49  *
50  * Speedups
51  *   -- LISTVIEW_GetNextItem needs to be rewritten. It is currently
52  *      linear in the number of items in the list, and this is
53  *      unacceptable for large lists.
54  *   -- if list is sorted by item text LISTVIEW_InsertItemT could use
55  *      binary search to calculate item index (e.g. DPA_Search()).
56  *      This requires sorted state to be reliably tracked in item modifiers.
57  *   -- we should keep an ordered array of coordinates in iconic mode.
58  *      This would allow framing items (iterator_frameditems),
59  *      and finding the nearest item (LVFI_NEARESTXY) a lot more efficiently.
60  *
61  * Flags
62  *   -- LVIF_COLUMNS
63  *   -- LVIF_GROUPID
64  *
65  * States
66  *   -- LVIS_ACTIVATING (not currently supported by comctl32.dll version 6.0)
67  *   -- LVIS_DROPHILITED
68  *
69  * Styles
70  *   -- LVS_NOLABELWRAP
71  *   -- LVS_NOSCROLL (see Q137520)
72  *   -- LVS_ALIGNTOP
73  *
74  * Extended Styles
75  *   -- LVS_EX_BORDERSELECT
76  *   -- LVS_EX_FLATSB
77  *   -- LVS_EX_INFOTIP
78  *   -- LVS_EX_LABELTIP
79  *   -- LVS_EX_MULTIWORKAREAS
80  *   -- LVS_EX_REGIONAL
81  *   -- LVS_EX_SIMPLESELECT
82  *   -- LVS_EX_TWOCLICKACTIVATE
83  *   -- LVS_EX_UNDERLINECOLD
84  *   -- LVS_EX_UNDERLINEHOT
85  *
86  * Notifications:
87  *   -- LVN_BEGINSCROLL, LVN_ENDSCROLL
88  *   -- LVN_GETINFOTIP
89  *   -- LVN_HOTTRACK
90  *   -- LVN_SETDISPINFO
91  *
92  * Messages:
93  *   -- LVM_ENABLEGROUPVIEW
94  *   -- LVM_GETBKIMAGE, LVM_SETBKIMAGE
95  *   -- LVM_GETGROUPINFO, LVM_SETGROUPINFO
96  *   -- LVM_GETGROUPMETRICS, LVM_SETGROUPMETRICS
97  *   -- LVM_GETINSERTMARK, LVM_SETINSERTMARK
98  *   -- LVM_GETINSERTMARKCOLOR, LVM_SETINSERTMARKCOLOR
99  *   -- LVM_GETINSERTMARKRECT
100  *   -- LVM_GETNUMBEROFWORKAREAS
101  *   -- LVM_GETOUTLINECOLOR, LVM_SETOUTLINECOLOR
102  *   -- LVM_GETSELECTEDCOLUMN, LVM_SETSELECTEDCOLUMN
103  *   -- LVM_GETISEARCHSTRINGW, LVM_GETISEARCHSTRINGA
104  *   -- LVM_GETTILEINFO, LVM_SETTILEINFO
105  *   -- LVM_GETTILEVIEWINFO, LVM_SETTILEVIEWINFO
106  *   -- LVM_GETWORKAREAS, LVM_SETWORKAREAS
107  *   -- LVM_HASGROUP, LVM_INSERTGROUP, LVM_REMOVEGROUP, LVM_REMOVEALLGROUPS
108  *   -- LVM_INSERTGROUPSORTED
109  *   -- LVM_INSERTMARKHITTEST
110  *   -- LVM_ISGROUPVIEWENABLED
111  *   -- LVM_MOVEGROUP
112  *   -- LVM_MOVEITEMTOGROUP
113  *   -- LVM_SETINFOTIP
114  *   -- LVM_SETTILEWIDTH
115  *   -- LVM_SORTGROUPS
116  *
117  * Macros:
118  *   -- ListView_GetHoverTime, ListView_SetHoverTime
119  *   -- ListView_GetISearchString
120  *   -- ListView_GetNumberOfWorkAreas
121  *   -- ListView_GetWorkAreas, ListView_SetWorkAreas
122  *
123  * Functions:
124  *   -- LVGroupComparE
125  */
126 
127 #include <assert.h>
128 #include <ctype.h>
129 #include <string.h>
130 #include <stdlib.h>
131 #include <stdarg.h>
132 #include <stdio.h>
133 
134 #include "windef.h"
135 #include "winbase.h"
136 #include "winnt.h"
137 #include "wingdi.h"
138 #include "winuser.h"
139 #include "winnls.h"
140 #include "commctrl.h"
141 #include "comctl32.h"
142 #include "uxtheme.h"
143 
144 #include "wine/debug.h"
145 
146 WINE_DEFAULT_DEBUG_CHANNEL(listview);
147 
148 typedef struct tagCOLUMN_INFO
149 {
150   RECT rcHeader;	/* tracks the header's rectangle */
151   INT fmt;		/* same as LVCOLUMN.fmt */
152   INT cxMin;
153 } COLUMN_INFO;
154 
155 typedef struct tagITEMHDR
156 {
157   LPWSTR pszText;
158   INT iImage;
159 } ITEMHDR, *LPITEMHDR;
160 
161 typedef struct tagSUBITEM_INFO
162 {
163   ITEMHDR hdr;
164   INT iSubItem;
165 } SUBITEM_INFO;
166 
167 typedef struct tagITEM_ID ITEM_ID;
168 
169 typedef struct tagITEM_INFO
170 {
171   ITEMHDR hdr;
172   UINT state;
173   LPARAM lParam;
174   INT iIndent;
175   ITEM_ID *id;
176 } ITEM_INFO;
177 
178 struct tagITEM_ID
179 {
180   UINT id;   /* item id */
181   HDPA item; /* link to item data */
182 };
183 
184 typedef struct tagRANGE
185 {
186   INT lower;
187   INT upper;
188 } RANGE;
189 
190 typedef struct tagRANGES
191 {
192   HDPA hdpa;
193 } *RANGES;
194 
195 typedef struct tagITERATOR
196 {
197   INT nItem;
198   INT nSpecial;
199   RANGE range;
200   RANGES ranges;
201   INT index;
202 } ITERATOR;
203 
204 typedef struct tagDELAYED_ITEM_EDIT
205 {
206   BOOL fEnabled;
207   INT iItem;
208 } DELAYED_ITEM_EDIT;
209 
210 enum notification_mask
211 {
212   NOTIFY_MASK_ITEM_CHANGE = 0x1,
213   NOTIFY_MASK_END_LABEL_EDIT = 0x2,
214   NOTIFY_MASK_UNMASK_ALL = 0xffffffff
215 };
216 
217 typedef struct tagLISTVIEW_INFO
218 {
219   /* control window */
220   HWND hwndSelf;
221   RECT rcList;                 /* This rectangle is really the window
222 				* client rectangle possibly reduced by the
223 				* horizontal scroll bar and/or header - see
224 				* LISTVIEW_UpdateSize. This rectangle offset
225 				* by the LISTVIEW_GetOrigin value is in
226 				* client coordinates   */
227 
228   /* notification window */
229   SHORT notifyFormat;
230   HWND hwndNotify;
231   DWORD notify_mask;
232   UINT uCallbackMask;
233 
234   /* tooltips */
235   HWND hwndToolTip;
236 
237   /* items */
238   INT nItemCount;		/* the number of items in the list */
239   HDPA hdpaItems;               /* array ITEM_INFO pointers */
240   HDPA hdpaItemIds;             /* array of ITEM_ID pointers */
241   HDPA hdpaPosX;		/* maintains the (X, Y) coordinates of the */
242   HDPA hdpaPosY;		/* items in LVS_ICON, and LVS_SMALLICON modes */
243   RANGES selectionRanges;
244   INT nSelectionMark;           /* item to start next multiselection from */
245   INT nHotItem;
246 
247   /* columns */
248   HDPA hdpaColumns;		/* array of COLUMN_INFO pointers */
249   BOOL colRectsDirty;		/* trigger column rectangles requery from header */
250 
251   /* item metrics */
252   BOOL bNoItemMetrics;		/* flags if item metrics are not yet computed */
253   INT nItemHeight;
254   INT nItemWidth;
255 
256   /* sorting */
257   PFNLVCOMPARE pfnCompare;      /* sorting callback pointer */
258   LPARAM lParamSort;
259 
260   /* style */
261   DWORD dwStyle;		/* the cached window GWL_STYLE */
262   DWORD dwLvExStyle;		/* extended listview style */
263   DWORD uView;			/* current view available through LVM_[G,S]ETVIEW */
264 
265   /* edit item */
266   HWND hwndEdit;
267   WNDPROC EditWndProc;
268   INT nEditLabelItem;
269   DELAYED_ITEM_EDIT itemEdit;   /* Pointer to this structure will be the timer ID */
270 
271   /* icons */
272   HIMAGELIST himlNormal;
273   HIMAGELIST himlSmall;
274   HIMAGELIST himlState;
275   SIZE iconSize;
276   BOOL autoSpacing;
277   SIZE iconSpacing;
278   SIZE iconStateSize;
279   POINT currIconPos;        /* this is the position next icon will be placed */
280 
281   /* header */
282   HWND hwndHeader;
283   INT xTrackLine;           /* The x coefficient of the track line or -1 if none */
284 
285   /* marquee selection */
286   BOOL bMarqueeSelect;      /* marquee selection/highlight underway */
287   BOOL bScrolling;
288   RECT marqueeRect;         /* absolute coordinates of marquee selection */
289   RECT marqueeDrawRect;     /* relative coordinates for drawing marquee */
290   POINT marqueeOrigin;      /* absolute coordinates of marquee click origin */
291 
292   /* focus drawing */
293   BOOL bFocus;              /* control has focus */
294   INT nFocusedItem;
295   RECT rcFocus;             /* focus bounds */
296 
297   /* colors */
298   HBRUSH hBkBrush;
299   COLORREF clrBk;
300   COLORREF clrText;
301   COLORREF clrTextBk;
302 #ifdef __REACTOS__
303   BOOL bDefaultBkColor;
304 #endif
305 
306   /* font */
307   HFONT hDefaultFont;
308   HFONT hFont;
309   INT ntmHeight;            /* Some cached metrics of the font used */
310   INT ntmMaxCharWidth;      /* by the listview to draw items */
311   INT nEllipsisWidth;
312 
313   /* mouse operation */
314   BOOL bLButtonDown;
315   BOOL bDragging;
316   POINT ptClickPos;         /* point where the user clicked */
317   INT nLButtonDownItem;     /* tracks item to reset multiselection on WM_LBUTTONUP */
318   DWORD dwHoverTime;
319   HCURSOR hHotCursor;
320   INT cWheelRemainder;
321 
322   /* keyboard operation */
323   DWORD lastKeyPressTimestamp;
324   WPARAM charCode;
325   INT nSearchParamLength;
326   WCHAR szSearchParam[ MAX_PATH ];
327 
328   /* painting */
329   BOOL bIsDrawing;         /* Drawing in progress */
330   INT nMeasureItemHeight;  /* WM_MEASUREITEM result */
331   BOOL redraw;             /* WM_SETREDRAW switch */
332 
333   /* misc */
334   DWORD iVersion;          /* CCM_[G,S]ETVERSION */
335 } LISTVIEW_INFO;
336 
337 /*
338  * constants
339  */
340 /* How many we debug buffer to allocate */
341 #define DEBUG_BUFFERS 20
342 /* The size of a single debug buffer */
343 #define DEBUG_BUFFER_SIZE 256
344 
345 /* Internal interface to LISTVIEW_HScroll and LISTVIEW_VScroll */
346 #define SB_INTERNAL      -1
347 
348 /* maximum size of a label */
349 #define DISP_TEXT_SIZE 260
350 
351 /* padding for items in list and small icon display modes */
352 #define WIDTH_PADDING 12
353 
354 /* padding for items in list, report and small icon display modes */
355 #define HEIGHT_PADDING 1
356 
357 /* offset of items in report display mode */
358 #define REPORT_MARGINX 2
359 
360 /* padding for icon in large icon display mode
361  *   ICON_TOP_PADDING_NOTHITABLE - space between top of box and area
362  *                                 that HITTEST will see.
363  *   ICON_TOP_PADDING_HITABLE - spacing between above and icon.
364  *   ICON_TOP_PADDING - sum of the two above.
365  *   ICON_BOTTOM_PADDING - between bottom of icon and top of text
366  *   LABEL_HOR_PADDING - between text and sides of box
367  *   LABEL_VERT_PADDING - between bottom of text and end of box
368  *
369  *   ICON_LR_PADDING - additional width above icon size.
370  *   ICON_LR_HALF - half of the above value
371  */
372 #define ICON_TOP_PADDING_NOTHITABLE  2
373 #define ICON_TOP_PADDING_HITABLE     2
374 #define ICON_TOP_PADDING (ICON_TOP_PADDING_NOTHITABLE + ICON_TOP_PADDING_HITABLE)
375 #define ICON_BOTTOM_PADDING          4
376 #define LABEL_HOR_PADDING            5
377 #define LABEL_VERT_PADDING           7
378 #define ICON_LR_PADDING              16
379 #define ICON_LR_HALF                 (ICON_LR_PADDING/2)
380 
381 /* default label width for items in list and small icon display modes */
382 #define DEFAULT_LABEL_WIDTH 40
383 /* maximum select rectangle width for empty text item in LV_VIEW_DETAILS */
384 #define MAX_EMPTYTEXT_SELECT_WIDTH 80
385 
386 /* default column width for items in list display mode */
387 #define DEFAULT_COLUMN_WIDTH 128
388 
389 /* Size of "line" scroll for V & H scrolls */
390 #define LISTVIEW_SCROLL_ICON_LINE_SIZE 37
391 
392 /* Padding between image and label */
393 #define IMAGE_PADDING  2
394 
395 /* Padding behind the label */
396 #define TRAILING_LABEL_PADDING  12
397 #define TRAILING_HEADER_PADDING  11
398 
399 /* Border for the icon caption */
400 #define CAPTION_BORDER  2
401 
402 /* Standard DrawText flags */
403 #define LV_ML_DT_FLAGS  (DT_TOP | DT_NOPREFIX | DT_EDITCONTROL | DT_CENTER | DT_WORDBREAK | DT_WORD_ELLIPSIS | DT_END_ELLIPSIS)
404 #define LV_FL_DT_FLAGS  (DT_TOP | DT_NOPREFIX | DT_EDITCONTROL | DT_CENTER | DT_WORDBREAK | DT_NOCLIP)
405 #define LV_SL_DT_FLAGS  (DT_VCENTER | DT_NOPREFIX | DT_EDITCONTROL | DT_SINGLELINE | DT_WORD_ELLIPSIS | DT_END_ELLIPSIS)
406 
407 /* Image index from state */
408 #define STATEIMAGEINDEX(x) (((x) & LVIS_STATEIMAGEMASK) >> 12)
409 
410 /* The time in milliseconds to reset the search in the list */
411 #define KEY_DELAY       450
412 
413 /* Dump the LISTVIEW_INFO structure to the debug channel */
414 #define LISTVIEW_DUMP(iP) do { \
415   TRACE("hwndSelf=%p, clrBk=0x%06x, clrText=0x%06x, clrTextBk=0x%06x, ItemHeight=%d, ItemWidth=%d, Style=0x%08x\n", \
416         iP->hwndSelf, iP->clrBk, iP->clrText, iP->clrTextBk, \
417         iP->nItemHeight, iP->nItemWidth, iP->dwStyle); \
418   TRACE("hwndSelf=%p, himlNor=%p, himlSml=%p, himlState=%p, Focused=%d, Hot=%d, exStyle=0x%08x, Focus=%d\n", \
419         iP->hwndSelf, iP->himlNormal, iP->himlSmall, iP->himlState, \
420         iP->nFocusedItem, iP->nHotItem, iP->dwLvExStyle, iP->bFocus ); \
421   TRACE("hwndSelf=%p, ntmH=%d, icSz.cx=%d, icSz.cy=%d, icSp.cx=%d, icSp.cy=%d, notifyFmt=%d\n", \
422         iP->hwndSelf, iP->ntmHeight, iP->iconSize.cx, iP->iconSize.cy, \
423         iP->iconSpacing.cx, iP->iconSpacing.cy, iP->notifyFormat); \
424   TRACE("hwndSelf=%p, rcList=%s\n", iP->hwndSelf, wine_dbgstr_rect(&iP->rcList)); \
425 } while(0)
426 
427 static const WCHAR themeClass[] = {'L','i','s','t','V','i','e','w',0};
428 
429 /*
430  * forward declarations
431  */
432 static BOOL LISTVIEW_GetItemT(const LISTVIEW_INFO *, LPLVITEMW, BOOL);
433 static void LISTVIEW_GetItemBox(const LISTVIEW_INFO *, INT, LPRECT);
434 static void LISTVIEW_GetItemOrigin(const LISTVIEW_INFO *, INT, LPPOINT);
435 static BOOL LISTVIEW_GetItemPosition(const LISTVIEW_INFO *, INT, LPPOINT);
436 static BOOL LISTVIEW_GetItemRect(const LISTVIEW_INFO *, INT, LPRECT);
437 static void LISTVIEW_GetOrigin(const LISTVIEW_INFO *, LPPOINT);
438 static BOOL LISTVIEW_GetViewRect(const LISTVIEW_INFO *, LPRECT);
439 static void LISTVIEW_UpdateSize(LISTVIEW_INFO *);
440 static LRESULT LISTVIEW_Command(LISTVIEW_INFO *, WPARAM, LPARAM);
441 static INT LISTVIEW_GetStringWidthT(const LISTVIEW_INFO *, LPCWSTR, BOOL);
442 static BOOL LISTVIEW_KeySelection(LISTVIEW_INFO *, INT, BOOL);
443 static UINT LISTVIEW_GetItemState(const LISTVIEW_INFO *, INT, UINT);
444 static BOOL LISTVIEW_SetItemState(LISTVIEW_INFO *, INT, const LVITEMW *);
445 static LRESULT LISTVIEW_VScroll(LISTVIEW_INFO *, INT, INT);
446 static LRESULT LISTVIEW_HScroll(LISTVIEW_INFO *, INT, INT);
447 static BOOL LISTVIEW_EnsureVisible(LISTVIEW_INFO *, INT, BOOL);
448 static HIMAGELIST LISTVIEW_SetImageList(LISTVIEW_INFO *, INT, HIMAGELIST);
449 static INT LISTVIEW_HitTest(const LISTVIEW_INFO *, LPLVHITTESTINFO, BOOL, BOOL);
450 static BOOL LISTVIEW_EndEditLabelT(LISTVIEW_INFO *, BOOL, BOOL);
451 static BOOL LISTVIEW_Scroll(LISTVIEW_INFO *, INT, INT);
452 
453 /******** Text handling functions *************************************/
454 
455 /* A text pointer is either NULL, LPSTR_TEXTCALLBACK, or points to a
456  * text string. The string may be ANSI or Unicode, in which case
457  * the boolean isW tells us the type of the string.
458  *
459  * The name of the function tell what type of strings it expects:
460  *   W: Unicode, T: ANSI/Unicode - function of isW
461  */
462 
463 static inline BOOL is_text(LPCWSTR text)
464 {
465     return text != NULL && text != LPSTR_TEXTCALLBACKW;
466 }
467 
468 static inline int textlenT(LPCWSTR text, BOOL isW)
469 {
470     return !is_text(text) ? 0 :
471 	   isW ? lstrlenW(text) : lstrlenA((LPCSTR)text);
472 }
473 
474 static inline void textcpynT(LPWSTR dest, BOOL isDestW, LPCWSTR src, BOOL isSrcW, INT max)
475 {
476     if (isDestW)
477 	if (isSrcW) lstrcpynW(dest, src, max);
478 	else MultiByteToWideChar(CP_ACP, 0, (LPCSTR)src, -1, dest, max);
479     else
480 	if (isSrcW) WideCharToMultiByte(CP_ACP, 0, src, -1, (LPSTR)dest, max, NULL, NULL);
481 	else lstrcpynA((LPSTR)dest, (LPCSTR)src, max);
482 }
483 
484 static inline LPWSTR textdupTtoW(LPCWSTR text, BOOL isW)
485 {
486     LPWSTR wstr = (LPWSTR)text;
487 
488     if (!isW && is_text(text))
489     {
490 	INT len = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)text, -1, NULL, 0);
491 	wstr = Alloc(len * sizeof(WCHAR));
492 	if (wstr) MultiByteToWideChar(CP_ACP, 0, (LPCSTR)text, -1, wstr, len);
493     }
494     TRACE("   wstr=%s\n", text == LPSTR_TEXTCALLBACKW ?  "(callback)" : debugstr_w(wstr));
495     return wstr;
496 }
497 
498 static inline void textfreeT(LPWSTR wstr, BOOL isW)
499 {
500     if (!isW && is_text(wstr)) Free (wstr);
501 }
502 
503 /*
504  * dest is a pointer to a Unicode string
505  * src is a pointer to a string (Unicode if isW, ANSI if !isW)
506  */
507 static BOOL textsetptrT(LPWSTR *dest, LPCWSTR src, BOOL isW)
508 {
509     BOOL bResult = TRUE;
510 
511     if (src == LPSTR_TEXTCALLBACKW)
512     {
513 	if (is_text(*dest)) Free(*dest);
514 	*dest = LPSTR_TEXTCALLBACKW;
515     }
516     else
517     {
518 	LPWSTR pszText = textdupTtoW(src, isW);
519 	if (*dest == LPSTR_TEXTCALLBACKW) *dest = NULL;
520 	bResult = Str_SetPtrW(dest, pszText);
521 	textfreeT(pszText, isW);
522     }
523     return bResult;
524 }
525 
526 /*
527  * compares a Unicode to a Unicode/ANSI text string
528  */
529 static inline int textcmpWT(LPCWSTR aw, LPCWSTR bt, BOOL isW)
530 {
531     if (!aw) return bt ? -1 : 0;
532     if (!bt) return 1;
533     if (aw == LPSTR_TEXTCALLBACKW)
534 	return bt == LPSTR_TEXTCALLBACKW ? 1 : -1;
535     if (bt != LPSTR_TEXTCALLBACKW)
536     {
537 	LPWSTR bw = textdupTtoW(bt, isW);
538 	int r = bw ? lstrcmpW(aw, bw) : 1;
539 	textfreeT(bw, isW);
540 	return r;
541     }
542 
543     return 1;
544 }
545 
546 static inline int lstrncmpiW(LPCWSTR s1, LPCWSTR s2, int n)
547 {
548     n = min(min(n, lstrlenW(s1)), lstrlenW(s2));
549     return CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE, s1, n, s2, n) - CSTR_EQUAL;
550 }
551 
552 /******** Debugging functions *****************************************/
553 
554 static inline LPCSTR debugtext_t(LPCWSTR text, BOOL isW)
555 {
556     if (text == LPSTR_TEXTCALLBACKW) return "(callback)";
557     return isW ? debugstr_w(text) : debugstr_a((LPCSTR)text);
558 }
559 
560 static inline LPCSTR debugtext_tn(LPCWSTR text, BOOL isW, INT n)
561 {
562     if (text == LPSTR_TEXTCALLBACKW) return "(callback)";
563     n = min(textlenT(text, isW), n);
564     return isW ? debugstr_wn(text, n) : debugstr_an((LPCSTR)text, n);
565 }
566 
567 static char* debug_getbuf(void)
568 {
569     static int index = 0;
570     static char buffers[DEBUG_BUFFERS][DEBUG_BUFFER_SIZE];
571     return buffers[index++ % DEBUG_BUFFERS];
572 }
573 
574 static inline const char* debugrange(const RANGE *lprng)
575 {
576     if (!lprng) return "(null)";
577     return wine_dbg_sprintf("[%d, %d]", lprng->lower, lprng->upper);
578 }
579 
580 static const char* debugscrollinfo(const SCROLLINFO *pScrollInfo)
581 {
582     char* buf = debug_getbuf(), *text = buf;
583     int len, size = DEBUG_BUFFER_SIZE;
584 
585     if (pScrollInfo == NULL) return "(null)";
586     len = snprintf(buf, size, "{cbSize=%u, ", pScrollInfo->cbSize);
587     if (len == -1) goto end;
588     buf += len; size -= len;
589     if (pScrollInfo->fMask & SIF_RANGE)
590 	len = snprintf(buf, size, "nMin=%d, nMax=%d, ", pScrollInfo->nMin, pScrollInfo->nMax);
591     else len = 0;
592     if (len == -1) goto end;
593     buf += len; size -= len;
594     if (pScrollInfo->fMask & SIF_PAGE)
595 	len = snprintf(buf, size, "nPage=%u, ", pScrollInfo->nPage);
596     else len = 0;
597     if (len == -1) goto end;
598     buf += len; size -= len;
599     if (pScrollInfo->fMask & SIF_POS)
600 	len = snprintf(buf, size, "nPos=%d, ", pScrollInfo->nPos);
601     else len = 0;
602     if (len == -1) goto end;
603     buf += len; size -= len;
604     if (pScrollInfo->fMask & SIF_TRACKPOS)
605 	len = snprintf(buf, size, "nTrackPos=%d, ", pScrollInfo->nTrackPos);
606     else len = 0;
607     if (len == -1) goto end;
608     buf += len;
609     goto undo;
610 end:
611     buf = text + strlen(text);
612 undo:
613     if (buf - text > 2) { buf[-2] = '}'; buf[-1] = 0; }
614     return text;
615 }
616 
617 static const char* debugnmlistview(const NMLISTVIEW *plvnm)
618 {
619     if (!plvnm) return "(null)";
620     return wine_dbg_sprintf("iItem=%d, iSubItem=%d, uNewState=0x%x,"
621 	         " uOldState=0x%x, uChanged=0x%x, ptAction=%s, lParam=%ld",
622 	         plvnm->iItem, plvnm->iSubItem, plvnm->uNewState, plvnm->uOldState,
623 		 plvnm->uChanged, wine_dbgstr_point(&plvnm->ptAction), plvnm->lParam);
624 }
625 
626 static const char* debuglvitem_t(const LVITEMW *lpLVItem, BOOL isW)
627 {
628     char* buf = debug_getbuf(), *text = buf;
629     int len, size = DEBUG_BUFFER_SIZE;
630 
631     if (lpLVItem == NULL) return "(null)";
632     len = snprintf(buf, size, "{iItem=%d, iSubItem=%d, ", lpLVItem->iItem, lpLVItem->iSubItem);
633     if (len == -1) goto end;
634     buf += len; size -= len;
635     if (lpLVItem->mask & LVIF_STATE)
636 	len = snprintf(buf, size, "state=%x, stateMask=%x, ", lpLVItem->state, lpLVItem->stateMask);
637     else len = 0;
638     if (len == -1) goto end;
639     buf += len; size -= len;
640     if (lpLVItem->mask & LVIF_TEXT)
641 	len = snprintf(buf, size, "pszText=%s, cchTextMax=%d, ", debugtext_tn(lpLVItem->pszText, isW, 80), lpLVItem->cchTextMax);
642     else len = 0;
643     if (len == -1) goto end;
644     buf += len; size -= len;
645     if (lpLVItem->mask & LVIF_IMAGE)
646 	len = snprintf(buf, size, "iImage=%d, ", lpLVItem->iImage);
647     else len = 0;
648     if (len == -1) goto end;
649     buf += len; size -= len;
650     if (lpLVItem->mask & LVIF_PARAM)
651 	len = snprintf(buf, size, "lParam=%lx, ", lpLVItem->lParam);
652     else len = 0;
653     if (len == -1) goto end;
654     buf += len; size -= len;
655     if (lpLVItem->mask & LVIF_INDENT)
656 	len = snprintf(buf, size, "iIndent=%d, ", lpLVItem->iIndent);
657     else len = 0;
658     if (len == -1) goto end;
659     buf += len;
660     goto undo;
661 end:
662     buf = text + strlen(text);
663 undo:
664     if (buf - text > 2) { buf[-2] = '}'; buf[-1] = 0; }
665     return text;
666 }
667 
668 static const char* debuglvcolumn_t(const LVCOLUMNW *lpColumn, BOOL isW)
669 {
670     char* buf = debug_getbuf(), *text = buf;
671     int len, size = DEBUG_BUFFER_SIZE;
672 
673     if (lpColumn == NULL) return "(null)";
674     len = snprintf(buf, size, "{");
675     if (len == -1) goto end;
676     buf += len; size -= len;
677     if (lpColumn->mask & LVCF_SUBITEM)
678 	len = snprintf(buf, size, "iSubItem=%d, ",  lpColumn->iSubItem);
679     else len = 0;
680     if (len == -1) goto end;
681     buf += len; size -= len;
682     if (lpColumn->mask & LVCF_FMT)
683 	len = snprintf(buf, size, "fmt=%x, ", lpColumn->fmt);
684     else len = 0;
685     if (len == -1) goto end;
686     buf += len; size -= len;
687     if (lpColumn->mask & LVCF_WIDTH)
688 	len = snprintf(buf, size, "cx=%d, ", lpColumn->cx);
689     else len = 0;
690     if (len == -1) goto end;
691     buf += len; size -= len;
692     if (lpColumn->mask & LVCF_TEXT)
693 	len = snprintf(buf, size, "pszText=%s, cchTextMax=%d, ", debugtext_tn(lpColumn->pszText, isW, 80), lpColumn->cchTextMax);
694     else len = 0;
695     if (len == -1) goto end;
696     buf += len; size -= len;
697     if (lpColumn->mask & LVCF_IMAGE)
698 	len = snprintf(buf, size, "iImage=%d, ", lpColumn->iImage);
699     else len = 0;
700     if (len == -1) goto end;
701     buf += len; size -= len;
702     if (lpColumn->mask & LVCF_ORDER)
703 	len = snprintf(buf, size, "iOrder=%d, ", lpColumn->iOrder);
704     else len = 0;
705     if (len == -1) goto end;
706     buf += len;
707     goto undo;
708 end:
709     buf = text + strlen(text);
710 undo:
711     if (buf - text > 2) { buf[-2] = '}'; buf[-1] = 0; }
712     return text;
713 }
714 
715 static const char* debuglvhittestinfo(const LVHITTESTINFO *lpht)
716 {
717     if (!lpht) return "(null)";
718 
719     return wine_dbg_sprintf("{pt=%s, flags=0x%x, iItem=%d, iSubItem=%d}",
720 		 wine_dbgstr_point(&lpht->pt), lpht->flags, lpht->iItem, lpht->iSubItem);
721 }
722 
723 /* Return the corresponding text for a given scroll value */
724 static inline LPCSTR debugscrollcode(int nScrollCode)
725 {
726   switch(nScrollCode)
727   {
728   case SB_LINELEFT: return "SB_LINELEFT";
729   case SB_LINERIGHT: return "SB_LINERIGHT";
730   case SB_PAGELEFT: return "SB_PAGELEFT";
731   case SB_PAGERIGHT: return "SB_PAGERIGHT";
732   case SB_THUMBPOSITION: return "SB_THUMBPOSITION";
733   case SB_THUMBTRACK: return "SB_THUMBTRACK";
734   case SB_ENDSCROLL: return "SB_ENDSCROLL";
735   case SB_INTERNAL: return "SB_INTERNAL";
736   default: return "unknown";
737   }
738 }
739 
740 
741 /******** Notification functions ************************************/
742 
743 static int get_ansi_notification(UINT unicodeNotificationCode)
744 {
745     switch (unicodeNotificationCode)
746     {
747     case LVN_BEGINLABELEDITA:
748     case LVN_BEGINLABELEDITW: return LVN_BEGINLABELEDITA;
749     case LVN_ENDLABELEDITA:
750     case LVN_ENDLABELEDITW: return LVN_ENDLABELEDITA;
751     case LVN_GETDISPINFOA:
752     case LVN_GETDISPINFOW: return LVN_GETDISPINFOA;
753     case LVN_SETDISPINFOA:
754     case LVN_SETDISPINFOW: return LVN_SETDISPINFOA;
755     case LVN_ODFINDITEMA:
756     case LVN_ODFINDITEMW: return LVN_ODFINDITEMA;
757     case LVN_GETINFOTIPA:
758     case LVN_GETINFOTIPW: return LVN_GETINFOTIPA;
759     /* header forwards */
760     case HDN_TRACKA:
761     case HDN_TRACKW: return HDN_TRACKA;
762     case HDN_ENDTRACKA:
763     case HDN_ENDTRACKW: return HDN_ENDTRACKA;
764     case HDN_BEGINDRAG: return HDN_BEGINDRAG;
765     case HDN_ENDDRAG: return HDN_ENDDRAG;
766     case HDN_ITEMCHANGINGA:
767     case HDN_ITEMCHANGINGW: return HDN_ITEMCHANGINGA;
768     case HDN_ITEMCHANGEDA:
769     case HDN_ITEMCHANGEDW: return HDN_ITEMCHANGEDA;
770     case HDN_ITEMCLICKA:
771     case HDN_ITEMCLICKW: return HDN_ITEMCLICKA;
772     case HDN_DIVIDERDBLCLICKA:
773     case HDN_DIVIDERDBLCLICKW: return HDN_DIVIDERDBLCLICKA;
774     default: break;
775     }
776     FIXME("unknown notification %x\n", unicodeNotificationCode);
777     return unicodeNotificationCode;
778 }
779 
780 /* forwards header notifications to listview parent */
781 static LRESULT notify_forward_header(const LISTVIEW_INFO *infoPtr, NMHEADERW *lpnmhW)
782 {
783     LPCWSTR text = NULL, filter = NULL;
784     LRESULT ret;
785     NMHEADERA *lpnmh = (NMHEADERA*) lpnmhW;
786 
787     /* on unicode format exit earlier */
788     if (infoPtr->notifyFormat == NFR_UNICODE)
789         return SendMessageW(infoPtr->hwndNotify, WM_NOTIFY, lpnmh->hdr.idFrom,
790                             (LPARAM)lpnmh);
791 
792     /* header always supplies unicode notifications,
793        all we have to do is to convert strings to ANSI */
794     if (lpnmh->pitem)
795     {
796         /* convert item text */
797         if (lpnmh->pitem->mask & HDI_TEXT)
798         {
799             text = (LPCWSTR)lpnmh->pitem->pszText;
800             lpnmh->pitem->pszText = NULL;
801             Str_SetPtrWtoA(&lpnmh->pitem->pszText, text);
802         }
803         /* convert filter text */
804         if ((lpnmh->pitem->mask & HDI_FILTER) && (lpnmh->pitem->type == HDFT_ISSTRING) &&
805              lpnmh->pitem->pvFilter)
806         {
807             filter = (LPCWSTR)((HD_TEXTFILTERA*)lpnmh->pitem->pvFilter)->pszText;
808             ((HD_TEXTFILTERA*)lpnmh->pitem->pvFilter)->pszText = NULL;
809             Str_SetPtrWtoA(&((HD_TEXTFILTERA*)lpnmh->pitem->pvFilter)->pszText, filter);
810         }
811     }
812     lpnmh->hdr.code = get_ansi_notification(lpnmh->hdr.code);
813 
814     ret = SendMessageW(infoPtr->hwndNotify, WM_NOTIFY, lpnmh->hdr.idFrom,
815                        (LPARAM)lpnmh);
816 
817     /* cleanup */
818     if(text)
819     {
820         Free(lpnmh->pitem->pszText);
821         lpnmh->pitem->pszText = (LPSTR)text;
822     }
823     if(filter)
824     {
825         Free(((HD_TEXTFILTERA*)lpnmh->pitem->pvFilter)->pszText);
826         ((HD_TEXTFILTERA*)lpnmh->pitem->pvFilter)->pszText = (LPSTR)filter;
827     }
828 
829     return ret;
830 }
831 
832 static LRESULT notify_hdr(const LISTVIEW_INFO *infoPtr, INT code, LPNMHDR pnmh)
833 {
834     LRESULT result;
835 
836     TRACE("(code=%d)\n", code);
837 
838     pnmh->hwndFrom = infoPtr->hwndSelf;
839     pnmh->idFrom = GetWindowLongPtrW(infoPtr->hwndSelf, GWLP_ID);
840     pnmh->code = code;
841     result = SendMessageW(infoPtr->hwndNotify, WM_NOTIFY, pnmh->idFrom, (LPARAM)pnmh);
842 
843     TRACE("  <= %ld\n", result);
844 
845     return result;
846 }
847 
848 static inline BOOL notify(const LISTVIEW_INFO *infoPtr, INT code)
849 {
850     NMHDR nmh;
851     HWND hwnd = infoPtr->hwndSelf;
852     notify_hdr(infoPtr, code, &nmh);
853     return IsWindow(hwnd);
854 }
855 
856 static inline void notify_itemactivate(const LISTVIEW_INFO *infoPtr, const LVHITTESTINFO *htInfo)
857 {
858     NMITEMACTIVATE nmia;
859     LVITEMW item;
860 
861     nmia.uNewState = 0;
862     nmia.uOldState = 0;
863     nmia.uChanged  = 0;
864     nmia.uKeyFlags = 0;
865 
866     item.mask = LVIF_PARAM|LVIF_STATE;
867     item.iItem = htInfo->iItem;
868     item.iSubItem = 0;
869     item.stateMask = (UINT)-1;
870     if (LISTVIEW_GetItemT(infoPtr, &item, TRUE)) {
871         nmia.lParam = item.lParam;
872         nmia.uOldState = item.state;
873         nmia.uNewState = item.state | LVIS_ACTIVATING;
874         nmia.uChanged  = LVIF_STATE;
875     }
876 
877     nmia.iItem = htInfo->iItem;
878     nmia.iSubItem = htInfo->iSubItem;
879     nmia.ptAction = htInfo->pt;
880 
881     if (GetKeyState(VK_SHIFT) & 0x8000) nmia.uKeyFlags |= LVKF_SHIFT;
882     if (GetKeyState(VK_CONTROL) & 0x8000) nmia.uKeyFlags |= LVKF_CONTROL;
883     if (GetKeyState(VK_MENU) & 0x8000) nmia.uKeyFlags |= LVKF_ALT;
884 
885     notify_hdr(infoPtr, LVN_ITEMACTIVATE, (LPNMHDR)&nmia);
886 }
887 
888 static inline LRESULT notify_listview(const LISTVIEW_INFO *infoPtr, INT code, LPNMLISTVIEW plvnm)
889 {
890     TRACE("(code=%d, plvnm=%s)\n", code, debugnmlistview(plvnm));
891     return notify_hdr(infoPtr, code, (LPNMHDR)plvnm);
892 }
893 
894 /* Handles NM_DBLCLK, NM_CLICK, NM_RDBLCLK, NM_RCLICK. Only NM_RCLICK return value is used. */
895 static BOOL notify_click(const LISTVIEW_INFO *infoPtr, INT code, const LVHITTESTINFO *lvht)
896 {
897     NMITEMACTIVATE nmia;
898     LVITEMW item;
899     HWND hwnd = infoPtr->hwndSelf;
900     LRESULT ret;
901 
902     TRACE("code=%d, lvht=%s\n", code, debuglvhittestinfo(lvht));
903     ZeroMemory(&nmia, sizeof(nmia));
904     nmia.iItem = lvht->iItem;
905     nmia.iSubItem = lvht->iSubItem;
906     nmia.ptAction = lvht->pt;
907     item.mask = LVIF_PARAM;
908     item.iItem = lvht->iItem;
909     item.iSubItem = 0;
910     if (LISTVIEW_GetItemT(infoPtr, &item, TRUE)) nmia.lParam = item.lParam;
911     ret = notify_hdr(infoPtr, code, (NMHDR*)&nmia);
912     return IsWindow(hwnd) && (code == NM_RCLICK ? !ret : TRUE);
913 }
914 
915 static BOOL notify_deleteitem(const LISTVIEW_INFO *infoPtr, INT nItem)
916 {
917     NMLISTVIEW nmlv;
918     LVITEMW item;
919     HWND hwnd = infoPtr->hwndSelf;
920 
921     ZeroMemory(&nmlv, sizeof (NMLISTVIEW));
922     nmlv.iItem = nItem;
923     item.mask = LVIF_PARAM;
924     item.iItem = nItem;
925     item.iSubItem = 0;
926     if (LISTVIEW_GetItemT(infoPtr, &item, TRUE)) nmlv.lParam = item.lParam;
927     notify_listview(infoPtr, LVN_DELETEITEM, &nmlv);
928     return IsWindow(hwnd);
929 }
930 
931 /*
932   Send notification. depends on dispinfoW having same
933   structure as dispinfoA.
934   infoPtr : listview struct
935   code : *Unicode* notification code
936   pdi : dispinfo structure (can be unicode or ansi)
937   isW : TRUE if dispinfo is Unicode
938 */
939 static BOOL notify_dispinfoT(const LISTVIEW_INFO *infoPtr, UINT code, LPNMLVDISPINFOW pdi, BOOL isW)
940 {
941     INT length = 0, ret_length;
942     LPWSTR buffer = NULL, ret_text;
943     BOOL return_ansi = FALSE;
944     BOOL return_unicode = FALSE;
945     BOOL ret;
946 
947     if ((pdi->item.mask & LVIF_TEXT) && is_text(pdi->item.pszText))
948     {
949 	return_unicode = ( isW && infoPtr->notifyFormat == NFR_ANSI);
950 	return_ansi    = (!isW && infoPtr->notifyFormat == NFR_UNICODE);
951     }
952 
953     ret_length = pdi->item.cchTextMax;
954     ret_text = pdi->item.pszText;
955 
956     if (return_unicode || return_ansi)
957     {
958         if (code != LVN_GETDISPINFOW)
959         {
960             length = return_ansi ?
961        		MultiByteToWideChar(CP_ACP, 0, (LPCSTR)pdi->item.pszText, -1, NULL, 0):
962        		WideCharToMultiByte(CP_ACP, 0, pdi->item.pszText, -1, NULL, 0, NULL, NULL);
963         }
964         else
965         {
966             length = pdi->item.cchTextMax;
967             *pdi->item.pszText = 0; /* make sure we don't process garbage */
968         }
969 
970         buffer = Alloc( (return_ansi ? sizeof(WCHAR) : sizeof(CHAR)) * length);
971         if (!buffer) return FALSE;
972 
973         if (return_ansi)
974             MultiByteToWideChar(CP_ACP, 0, (LPCSTR)pdi->item.pszText, -1,
975 	                        buffer, length);
976         else
977             WideCharToMultiByte(CP_ACP, 0, pdi->item.pszText, -1, (LPSTR) buffer,
978 	                        length, NULL, NULL);
979 
980         pdi->item.pszText = buffer;
981         pdi->item.cchTextMax = length;
982     }
983 
984     if (infoPtr->notifyFormat == NFR_ANSI)
985         code = get_ansi_notification(code);
986 
987     TRACE(" pdi->item=%s\n", debuglvitem_t(&pdi->item, infoPtr->notifyFormat != NFR_ANSI));
988     ret = notify_hdr(infoPtr, code, &pdi->hdr);
989     TRACE(" resulting code=%d\n", pdi->hdr.code);
990 
991     if (return_ansi || return_unicode)
992     {
993         if (return_ansi && (pdi->hdr.code == LVN_GETDISPINFOA))
994         {
995             strcpy((char*)ret_text, (char*)pdi->item.pszText);
996         }
997         else if (return_unicode && (pdi->hdr.code == LVN_GETDISPINFOW))
998         {
999             lstrcpyW(ret_text, pdi->item.pszText);
1000         }
1001         else if (return_ansi) /* note : pointer can be changed by app ! */
1002         {
1003 	    WideCharToMultiByte(CP_ACP, 0, pdi->item.pszText, -1, (LPSTR) ret_text,
1004                 ret_length, NULL, NULL);
1005         }
1006         else
1007             MultiByteToWideChar(CP_ACP, 0, (LPSTR) pdi->item.pszText, -1,
1008                 ret_text, ret_length);
1009 
1010         pdi->item.pszText = ret_text; /* restores our buffer */
1011         pdi->item.cchTextMax = ret_length;
1012 
1013         Free(buffer);
1014         return ret;
1015     }
1016 
1017     /* if dispinfo holder changed notification code then convert */
1018     if (!isW && (pdi->hdr.code == LVN_GETDISPINFOW) && (pdi->item.mask & LVIF_TEXT))
1019     {
1020         length = WideCharToMultiByte(CP_ACP, 0, pdi->item.pszText, -1, NULL, 0, NULL, NULL);
1021 
1022         buffer = Alloc(length * sizeof(CHAR));
1023         if (!buffer) return FALSE;
1024 
1025         WideCharToMultiByte(CP_ACP, 0, pdi->item.pszText, -1, (LPSTR) buffer,
1026                 ret_length, NULL, NULL);
1027 
1028         strcpy((LPSTR)pdi->item.pszText, (LPSTR)buffer);
1029         Free(buffer);
1030     }
1031 
1032     return ret;
1033 }
1034 
1035 static void customdraw_fill(NMLVCUSTOMDRAW *lpnmlvcd, const LISTVIEW_INFO *infoPtr, HDC hdc,
1036 			    const RECT *rcBounds, const LVITEMW *lplvItem)
1037 {
1038     ZeroMemory(lpnmlvcd, sizeof(NMLVCUSTOMDRAW));
1039     lpnmlvcd->nmcd.hdc = hdc;
1040     lpnmlvcd->nmcd.rc = *rcBounds;
1041     lpnmlvcd->clrTextBk = infoPtr->clrTextBk;
1042     lpnmlvcd->clrText   = infoPtr->clrText;
1043     if (!lplvItem) return;
1044     lpnmlvcd->nmcd.dwItemSpec = lplvItem->iItem + 1;
1045     lpnmlvcd->iSubItem = lplvItem->iSubItem;
1046     if (lplvItem->state & LVIS_SELECTED) lpnmlvcd->nmcd.uItemState |= CDIS_SELECTED;
1047     if (lplvItem->state & LVIS_FOCUSED) lpnmlvcd->nmcd.uItemState |= CDIS_FOCUS;
1048     if (lplvItem->iItem == infoPtr->nHotItem) lpnmlvcd->nmcd.uItemState |= CDIS_HOT;
1049     lpnmlvcd->nmcd.lItemlParam = lplvItem->lParam;
1050 }
1051 
1052 static inline DWORD notify_customdraw (const LISTVIEW_INFO *infoPtr, DWORD dwDrawStage, NMLVCUSTOMDRAW *lpnmlvcd)
1053 {
1054     BOOL isForItem = (lpnmlvcd->nmcd.dwItemSpec != 0);
1055     DWORD result;
1056 
1057     lpnmlvcd->nmcd.dwDrawStage = dwDrawStage;
1058     if (isForItem) lpnmlvcd->nmcd.dwDrawStage |= CDDS_ITEM;
1059     if (lpnmlvcd->iSubItem) lpnmlvcd->nmcd.dwDrawStage |= CDDS_SUBITEM;
1060     if (isForItem) lpnmlvcd->nmcd.dwItemSpec--;
1061     result = notify_hdr(infoPtr, NM_CUSTOMDRAW, &lpnmlvcd->nmcd.hdr);
1062     if (isForItem) lpnmlvcd->nmcd.dwItemSpec++;
1063     return result;
1064 }
1065 
1066 static void prepaint_setup (const LISTVIEW_INFO *infoPtr, HDC hdc, NMLVCUSTOMDRAW *lpnmlvcd, BOOL SubItem)
1067 {
1068     COLORREF backcolor, textcolor;
1069 
1070     /* apparently, for selected items, we have to override the returned values */
1071     if (!SubItem || (infoPtr->dwLvExStyle & LVS_EX_FULLROWSELECT))
1072     {
1073         if (lpnmlvcd->nmcd.uItemState & CDIS_SELECTED)
1074         {
1075             if (infoPtr->bFocus)
1076             {
1077                 lpnmlvcd->clrTextBk = comctl32_color.clrHighlight;
1078                 lpnmlvcd->clrText   = comctl32_color.clrHighlightText;
1079             }
1080             else if (infoPtr->dwStyle & LVS_SHOWSELALWAYS)
1081             {
1082                 lpnmlvcd->clrTextBk = comctl32_color.clr3dFace;
1083                 lpnmlvcd->clrText   = comctl32_color.clrBtnText;
1084             }
1085         }
1086     }
1087 
1088     backcolor = lpnmlvcd->clrTextBk;
1089     textcolor = lpnmlvcd->clrText;
1090 
1091     if (backcolor == CLR_DEFAULT)
1092         backcolor = comctl32_color.clrWindow;
1093     if (textcolor == CLR_DEFAULT)
1094         textcolor = comctl32_color.clrWindowText;
1095 
1096     /* Set the text attributes */
1097     if (backcolor != CLR_NONE)
1098     {
1099 	SetBkMode(hdc, OPAQUE);
1100 	SetBkColor(hdc, backcolor);
1101     }
1102     else
1103 	SetBkMode(hdc, TRANSPARENT);
1104     SetTextColor(hdc, textcolor);
1105 }
1106 
1107 static inline DWORD notify_postpaint (const LISTVIEW_INFO *infoPtr, NMLVCUSTOMDRAW *lpnmlvcd)
1108 {
1109     return notify_customdraw(infoPtr, CDDS_POSTPAINT, lpnmlvcd);
1110 }
1111 
1112 /* returns TRUE when repaint needed, FALSE otherwise */
1113 static BOOL notify_measureitem(LISTVIEW_INFO *infoPtr)
1114 {
1115     MEASUREITEMSTRUCT mis;
1116     mis.CtlType = ODT_LISTVIEW;
1117     mis.CtlID = GetWindowLongPtrW(infoPtr->hwndSelf, GWLP_ID);
1118     mis.itemID = -1;
1119     mis.itemWidth = 0;
1120     mis.itemData = 0;
1121     mis.itemHeight= infoPtr->nItemHeight;
1122     SendMessageW(infoPtr->hwndNotify, WM_MEASUREITEM, mis.CtlID, (LPARAM)&mis);
1123     if (infoPtr->nItemHeight != max(mis.itemHeight, 1))
1124     {
1125         infoPtr->nMeasureItemHeight = infoPtr->nItemHeight = max(mis.itemHeight, 1);
1126         return TRUE;
1127     }
1128     return FALSE;
1129 }
1130 
1131 /******** Item iterator functions **********************************/
1132 
1133 static RANGES ranges_create(int count);
1134 static void ranges_destroy(RANGES ranges);
1135 static BOOL ranges_add(RANGES ranges, RANGE range);
1136 static BOOL ranges_del(RANGES ranges, RANGE range);
1137 static void ranges_dump(RANGES ranges);
1138 
1139 static inline BOOL ranges_additem(RANGES ranges, INT nItem)
1140 {
1141     RANGE range = { nItem, nItem + 1 };
1142 
1143     return ranges_add(ranges, range);
1144 }
1145 
1146 static inline BOOL ranges_delitem(RANGES ranges, INT nItem)
1147 {
1148     RANGE range = { nItem, nItem + 1 };
1149 
1150     return ranges_del(ranges, range);
1151 }
1152 
1153 /***
1154  * ITERATOR DOCUMENTATION
1155  *
1156  * The iterator functions allow for easy, and convenient iteration
1157  * over items of interest in the list. Typically, you create an
1158  * iterator, use it, and destroy it, as such:
1159  *   ITERATOR i;
1160  *
1161  *   iterator_xxxitems(&i, ...);
1162  *   while (iterator_{prev,next}(&i)
1163  *   {
1164  *       //code which uses i.nItem
1165  *   }
1166  *   iterator_destroy(&i);
1167  *
1168  *   where xxx is either: framed, or visible.
1169  * Note that it is important that the code destroys the iterator
1170  * after it's done with it, as the creation of the iterator may
1171  * allocate memory, which thus needs to be freed.
1172  *
1173  * You can iterate both forwards, and backwards through the list,
1174  * by using iterator_next or iterator_prev respectively.
1175  *
1176  * Lower numbered items are draw on top of higher number items in
1177  * LVS_ICON, and LVS_SMALLICON (which are the only modes where
1178  * items may overlap). So, to test items, you should use
1179  *    iterator_next
1180  * which lists the items top to bottom (in Z-order).
1181  * For drawing items, you should use
1182  *    iterator_prev
1183  * which lists the items bottom to top (in Z-order).
1184  * If you keep iterating over the items after the end-of-items
1185  * marker (-1) is returned, the iterator will start from the
1186  * beginning. Typically, you don't need to test for -1,
1187  * because iterator_{next,prev} will return TRUE if more items
1188  * are to be iterated over, or FALSE otherwise.
1189  *
1190  * Note: the iterator is defined to be bidirectional. That is,
1191  *       any number of prev followed by any number of next, or
1192  *       five versa, should leave the iterator at the same item:
1193  *           prev * n, next * n = next * n, prev * n
1194  *
1195  * The iterator has a notion of an out-of-order, special item,
1196  * which sits at the start of the list. This is used in
1197  * LVS_ICON, and LVS_SMALLICON mode to handle the focused item,
1198  * which needs to be first, as it may overlap other items.
1199  *
1200  * The code is a bit messy because we have:
1201  *   - a special item to deal with
1202  *   - simple range, or composite range
1203  *   - empty range.
1204  * If you find bugs, or want to add features, please make sure you
1205  * always check/modify *both* iterator_prev, and iterator_next.
1206  */
1207 
1208 /****
1209  * This function iterates through the items in increasing order,
1210  * but prefixed by the special item, then -1. That is:
1211  *    special, 1, 2, 3, ..., n, -1.
1212  * Each item is listed only once.
1213  */
1214 static inline BOOL iterator_next(ITERATOR* i)
1215 {
1216     if (i->nItem == -1)
1217     {
1218 	i->nItem = i->nSpecial;
1219 	if (i->nItem != -1) return TRUE;
1220     }
1221     if (i->nItem == i->nSpecial)
1222     {
1223 	if (i->ranges) i->index = 0;
1224 	goto pickarange;
1225     }
1226 
1227     i->nItem++;
1228 testitem:
1229     if (i->nItem == i->nSpecial) i->nItem++;
1230     if (i->nItem < i->range.upper) return TRUE;
1231 
1232 pickarange:
1233     if (i->ranges)
1234     {
1235 	if (i->index < DPA_GetPtrCount(i->ranges->hdpa))
1236 	    i->range = *(RANGE*)DPA_GetPtr(i->ranges->hdpa, i->index++);
1237 	else goto end;
1238     }
1239     else if (i->nItem >= i->range.upper) goto end;
1240 
1241     i->nItem = i->range.lower;
1242     if (i->nItem >= 0) goto testitem;
1243 end:
1244     i->nItem = -1;
1245     return FALSE;
1246 }
1247 
1248 /****
1249  * This function iterates through the items in decreasing order,
1250  * followed by the special item, then -1. That is:
1251  *    n, n-1, ..., 3, 2, 1, special, -1.
1252  * Each item is listed only once.
1253  */
1254 static inline BOOL iterator_prev(ITERATOR* i)
1255 {
1256     BOOL start = FALSE;
1257 
1258     if (i->nItem == -1)
1259     {
1260 	start = TRUE;
1261 	if (i->ranges) i->index = DPA_GetPtrCount(i->ranges->hdpa);
1262 	goto pickarange;
1263     }
1264     if (i->nItem == i->nSpecial)
1265     {
1266 	i->nItem = -1;
1267 	return FALSE;
1268     }
1269 
1270 testitem:
1271     i->nItem--;
1272     if (i->nItem == i->nSpecial) i->nItem--;
1273     if (i->nItem >= i->range.lower) return TRUE;
1274 
1275 pickarange:
1276     if (i->ranges)
1277     {
1278 	if (i->index > 0)
1279 	    i->range = *(RANGE*)DPA_GetPtr(i->ranges->hdpa, --i->index);
1280 	else goto end;
1281     }
1282     else if (!start && i->nItem < i->range.lower) goto end;
1283 
1284     i->nItem = i->range.upper;
1285     if (i->nItem > 0) goto testitem;
1286 end:
1287     return (i->nItem = i->nSpecial) != -1;
1288 }
1289 
1290 static RANGE iterator_range(const ITERATOR *i)
1291 {
1292     RANGE range;
1293 
1294     if (!i->ranges) return i->range;
1295 
1296     if (DPA_GetPtrCount(i->ranges->hdpa) > 0)
1297     {
1298         range.lower = (*(RANGE*)DPA_GetPtr(i->ranges->hdpa, 0)).lower;
1299         range.upper = (*(RANGE*)DPA_GetPtr(i->ranges->hdpa, DPA_GetPtrCount(i->ranges->hdpa) - 1)).upper;
1300     }
1301     else range.lower = range.upper = 0;
1302 
1303     return range;
1304 }
1305 
1306 /***
1307  * Releases resources associated with this iterator.
1308  */
1309 static inline void iterator_destroy(const ITERATOR *i)
1310 {
1311     ranges_destroy(i->ranges);
1312 }
1313 
1314 /***
1315  * Create an empty iterator.
1316  */
1317 static inline void iterator_empty(ITERATOR* i)
1318 {
1319     ZeroMemory(i, sizeof(*i));
1320     i->nItem = i->nSpecial = i->range.lower = i->range.upper = -1;
1321 }
1322 
1323 /***
1324  * Create an iterator over a range.
1325  */
1326 static inline void iterator_rangeitems(ITERATOR* i, RANGE range)
1327 {
1328     iterator_empty(i);
1329     i->range = range;
1330 }
1331 
1332 /***
1333  * Create an iterator over a bunch of ranges.
1334  * Please note that the iterator will take ownership of the ranges,
1335  * and will free them upon destruction.
1336  */
1337 static inline void iterator_rangesitems(ITERATOR* i, RANGES ranges)
1338 {
1339     iterator_empty(i);
1340     i->ranges = ranges;
1341 }
1342 
1343 /***
1344  * Creates an iterator over the items which intersect frame.
1345  * Uses absolute coordinates rather than compensating for the current offset.
1346  */
1347 static BOOL iterator_frameditems_absolute(ITERATOR* i, const LISTVIEW_INFO* infoPtr, const RECT *frame)
1348 {
1349     RECT rcItem, rcTemp;
1350     RANGES ranges;
1351 
1352     TRACE("(frame=%s)\n", wine_dbgstr_rect(frame));
1353 
1354     /* in case we fail, we want to return an empty iterator */
1355     iterator_empty(i);
1356 
1357     if (infoPtr->nItemCount == 0)
1358         return TRUE;
1359 
1360     if (infoPtr->uView == LV_VIEW_ICON || infoPtr->uView == LV_VIEW_SMALLICON)
1361     {
1362 	INT nItem;
1363 
1364 	if (infoPtr->uView == LV_VIEW_ICON && infoPtr->nFocusedItem != -1)
1365 	{
1366 	    LISTVIEW_GetItemBox(infoPtr, infoPtr->nFocusedItem, &rcItem);
1367 	    if (IntersectRect(&rcTemp, &rcItem, frame))
1368 		i->nSpecial = infoPtr->nFocusedItem;
1369 	}
1370 	if (!(ranges = ranges_create(50))) return FALSE;
1371 	iterator_rangesitems(i, ranges);
1372 	/* to do better here, we need to have PosX, and PosY sorted */
1373 	TRACE("building icon ranges:\n");
1374 	for (nItem = 0; nItem < infoPtr->nItemCount; nItem++)
1375 	{
1376             rcItem.left = (LONG_PTR)DPA_GetPtr(infoPtr->hdpaPosX, nItem);
1377 	    rcItem.top = (LONG_PTR)DPA_GetPtr(infoPtr->hdpaPosY, nItem);
1378 	    rcItem.right = rcItem.left + infoPtr->nItemWidth;
1379 	    rcItem.bottom = rcItem.top + infoPtr->nItemHeight;
1380 	    if (IntersectRect(&rcTemp, &rcItem, frame))
1381 		ranges_additem(i->ranges, nItem);
1382 	}
1383 	return TRUE;
1384     }
1385     else if (infoPtr->uView == LV_VIEW_DETAILS)
1386     {
1387 	RANGE range;
1388 
1389 	if (frame->left >= infoPtr->nItemWidth) return TRUE;
1390 	if (frame->top >= infoPtr->nItemHeight * infoPtr->nItemCount) return TRUE;
1391 
1392 	range.lower = max(frame->top / infoPtr->nItemHeight, 0);
1393 	range.upper = min((frame->bottom - 1) / infoPtr->nItemHeight, infoPtr->nItemCount - 1) + 1;
1394 	if (range.upper <= range.lower) return TRUE;
1395 	iterator_rangeitems(i, range);
1396 	TRACE("    report=%s\n", debugrange(&i->range));
1397     }
1398     else
1399     {
1400 	INT nPerCol = max((infoPtr->rcList.bottom - infoPtr->rcList.top) / infoPtr->nItemHeight, 1);
1401 	INT nFirstRow = max(frame->top / infoPtr->nItemHeight, 0);
1402 	INT nLastRow = min((frame->bottom - 1) / infoPtr->nItemHeight, nPerCol - 1);
1403 	INT nFirstCol;
1404 	INT nLastCol;
1405 	INT lower;
1406 	RANGE item_range;
1407 	INT nCol;
1408 
1409 	if (infoPtr->nItemWidth)
1410 	{
1411 	    nFirstCol = max(frame->left / infoPtr->nItemWidth, 0);
1412             nLastCol  = min((frame->right - 1) / infoPtr->nItemWidth, (infoPtr->nItemCount + nPerCol - 1) / nPerCol);
1413 	}
1414 	else
1415 	{
1416 	    nFirstCol = max(frame->left, 0);
1417             nLastCol  = min(frame->right - 1, (infoPtr->nItemCount + nPerCol - 1) / nPerCol);
1418 	}
1419 
1420 	lower = nFirstCol * nPerCol + nFirstRow;
1421 
1422 	TRACE("nPerCol=%d, nFirstRow=%d, nLastRow=%d, nFirstCol=%d, nLastCol=%d, lower=%d\n",
1423 	      nPerCol, nFirstRow, nLastRow, nFirstCol, nLastCol, lower);
1424 
1425 	if (nLastCol < nFirstCol || nLastRow < nFirstRow) return TRUE;
1426 
1427 	if (!(ranges = ranges_create(nLastCol - nFirstCol + 1))) return FALSE;
1428 	iterator_rangesitems(i, ranges);
1429 	TRACE("building list ranges:\n");
1430 	for (nCol = nFirstCol; nCol <= nLastCol; nCol++)
1431 	{
1432 	    item_range.lower = nCol * nPerCol + nFirstRow;
1433 	    if(item_range.lower >= infoPtr->nItemCount) break;
1434 	    item_range.upper = min(nCol * nPerCol + nLastRow + 1, infoPtr->nItemCount);
1435 	    TRACE("   list=%s\n", debugrange(&item_range));
1436 	    ranges_add(i->ranges, item_range);
1437 	}
1438     }
1439 
1440     return TRUE;
1441 }
1442 
1443 /***
1444  * Creates an iterator over the items which intersect lprc.
1445  */
1446 static BOOL iterator_frameditems(ITERATOR* i, const LISTVIEW_INFO* infoPtr, const RECT *lprc)
1447 {
1448     RECT frame = *lprc;
1449     POINT Origin;
1450 
1451     TRACE("(lprc=%s)\n", wine_dbgstr_rect(lprc));
1452 
1453     LISTVIEW_GetOrigin(infoPtr, &Origin);
1454     OffsetRect(&frame, -Origin.x, -Origin.y);
1455 
1456     return iterator_frameditems_absolute(i, infoPtr, &frame);
1457 }
1458 
1459 /***
1460  * Creates an iterator over the items which intersect the visible region of hdc.
1461  */
1462 static BOOL iterator_visibleitems(ITERATOR *i, const LISTVIEW_INFO *infoPtr, HDC  hdc)
1463 {
1464     POINT Origin, Position;
1465     RECT rcItem, rcClip;
1466     INT rgntype;
1467 
1468     rgntype = GetClipBox(hdc, &rcClip);
1469     if (rgntype == NULLREGION)
1470     {
1471         iterator_empty(i);
1472         return TRUE;
1473     }
1474     if (!iterator_frameditems(i, infoPtr, &rcClip)) return FALSE;
1475     if (rgntype == SIMPLEREGION) return TRUE;
1476 
1477     /* first deal with the special item */
1478     if (i->nSpecial != -1)
1479     {
1480 	LISTVIEW_GetItemBox(infoPtr, i->nSpecial, &rcItem);
1481 	if (!RectVisible(hdc, &rcItem)) i->nSpecial = -1;
1482     }
1483 
1484     /* if we can't deal with the region, we'll just go with the simple range */
1485     LISTVIEW_GetOrigin(infoPtr, &Origin);
1486     TRACE("building visible range:\n");
1487     if (!i->ranges && i->range.lower < i->range.upper)
1488     {
1489 	if (!(i->ranges = ranges_create(50))) return TRUE;
1490 	if (!ranges_add(i->ranges, i->range))
1491         {
1492 	    ranges_destroy(i->ranges);
1493 	    i->ranges = 0;
1494 	    return TRUE;
1495         }
1496     }
1497 
1498     /* now delete the invisible items from the list */
1499     while(iterator_next(i))
1500     {
1501 	LISTVIEW_GetItemOrigin(infoPtr, i->nItem, &Position);
1502 	rcItem.left = (infoPtr->uView == LV_VIEW_DETAILS) ? Origin.x : Position.x + Origin.x;
1503 	rcItem.top = Position.y + Origin.y;
1504 	rcItem.right = rcItem.left + infoPtr->nItemWidth;
1505 	rcItem.bottom = rcItem.top + infoPtr->nItemHeight;
1506 	if (!RectVisible(hdc, &rcItem))
1507 	    ranges_delitem(i->ranges, i->nItem);
1508     }
1509     /* the iterator should restart on the next iterator_next */
1510     TRACE("done\n");
1511 
1512     return TRUE;
1513 }
1514 
1515 /* Remove common elements from two iterators */
1516 /* Passed iterators have to point on the first elements */
1517 static BOOL iterator_remove_common_items(ITERATOR *iter1, ITERATOR *iter2)
1518 {
1519     if(!iter1->ranges || !iter2->ranges) {
1520         int lower, upper;
1521 
1522         if(iter1->ranges || iter2->ranges ||
1523                 (iter1->range.lower<iter2->range.lower && iter1->range.upper>iter2->range.upper) ||
1524                 (iter1->range.lower>iter2->range.lower && iter1->range.upper<iter2->range.upper)) {
1525             ERR("result is not a one range iterator\n");
1526             return FALSE;
1527         }
1528 
1529         if(iter1->range.lower==-1 || iter2->range.lower==-1)
1530             return TRUE;
1531 
1532         lower = iter1->range.lower;
1533         upper = iter1->range.upper;
1534 
1535         if(lower < iter2->range.lower)
1536             iter1->range.upper = iter2->range.lower;
1537         else if(upper > iter2->range.upper)
1538             iter1->range.lower = iter2->range.upper;
1539         else
1540             iter1->range.lower = iter1->range.upper = -1;
1541 
1542         if(iter2->range.lower < lower)
1543             iter2->range.upper = lower;
1544         else if(iter2->range.upper > upper)
1545             iter2->range.lower = upper;
1546         else
1547             iter2->range.lower = iter2->range.upper = -1;
1548 
1549         return TRUE;
1550     }
1551 
1552     iterator_next(iter1);
1553     iterator_next(iter2);
1554 
1555     while(1) {
1556         if(iter1->nItem==-1 || iter2->nItem==-1)
1557             break;
1558 
1559         if(iter1->nItem == iter2->nItem) {
1560             int delete = iter1->nItem;
1561 
1562             iterator_prev(iter1);
1563             iterator_prev(iter2);
1564             ranges_delitem(iter1->ranges, delete);
1565             ranges_delitem(iter2->ranges, delete);
1566             iterator_next(iter1);
1567             iterator_next(iter2);
1568         } else if(iter1->nItem > iter2->nItem)
1569             iterator_next(iter2);
1570         else
1571             iterator_next(iter1);
1572     }
1573 
1574     iter1->nItem = iter1->range.lower = iter1->range.upper = -1;
1575     iter2->nItem = iter2->range.lower = iter2->range.upper = -1;
1576     return TRUE;
1577 }
1578 
1579 /******** Misc helper functions ************************************/
1580 
1581 static inline LRESULT CallWindowProcT(WNDPROC proc, HWND hwnd, UINT uMsg,
1582 		                      WPARAM wParam, LPARAM lParam, BOOL isW)
1583 {
1584     if (isW) return CallWindowProcW(proc, hwnd, uMsg, wParam, lParam);
1585     else return CallWindowProcA(proc, hwnd, uMsg, wParam, lParam);
1586 }
1587 
1588 static inline BOOL is_autoarrange(const LISTVIEW_INFO *infoPtr)
1589 {
1590     return (infoPtr->dwStyle & LVS_AUTOARRANGE) &&
1591         (infoPtr->uView == LV_VIEW_ICON || infoPtr->uView == LV_VIEW_SMALLICON);
1592 }
1593 
1594 static void toggle_checkbox_state(LISTVIEW_INFO *infoPtr, INT nItem)
1595 {
1596     DWORD state = STATEIMAGEINDEX(LISTVIEW_GetItemState(infoPtr, nItem, LVIS_STATEIMAGEMASK));
1597     if(state == 1 || state == 2)
1598     {
1599         LVITEMW lvitem;
1600         state ^= 3;
1601         lvitem.state = INDEXTOSTATEIMAGEMASK(state);
1602         lvitem.stateMask = LVIS_STATEIMAGEMASK;
1603         LISTVIEW_SetItemState(infoPtr, nItem, &lvitem);
1604     }
1605 }
1606 
1607 /* this should be called after window style got updated,
1608    it used to reset view state to match current window style */
1609 static inline void map_style_view(LISTVIEW_INFO *infoPtr)
1610 {
1611     switch (infoPtr->dwStyle & LVS_TYPEMASK)
1612     {
1613     case LVS_ICON:
1614         infoPtr->uView = LV_VIEW_ICON;
1615         break;
1616     case LVS_REPORT:
1617         infoPtr->uView = LV_VIEW_DETAILS;
1618         break;
1619     case LVS_SMALLICON:
1620         infoPtr->uView = LV_VIEW_SMALLICON;
1621         break;
1622     case LVS_LIST:
1623         infoPtr->uView = LV_VIEW_LIST;
1624     }
1625 }
1626 
1627 /* computes next item id value */
1628 static DWORD get_next_itemid(const LISTVIEW_INFO *infoPtr)
1629 {
1630     INT count = DPA_GetPtrCount(infoPtr->hdpaItemIds);
1631 
1632     if (count > 0)
1633     {
1634         ITEM_ID *lpID = DPA_GetPtr(infoPtr->hdpaItemIds, count - 1);
1635         return lpID->id + 1;
1636     }
1637     return 0;
1638 }
1639 
1640 /******** Internal API functions ************************************/
1641 
1642 static inline COLUMN_INFO * LISTVIEW_GetColumnInfo(const LISTVIEW_INFO *infoPtr, INT nSubItem)
1643 {
1644     static COLUMN_INFO mainItem;
1645 
1646     if (nSubItem == 0 && DPA_GetPtrCount(infoPtr->hdpaColumns) == 0) return &mainItem;
1647     assert (nSubItem >= 0 && nSubItem < DPA_GetPtrCount(infoPtr->hdpaColumns));
1648 
1649     /* update cached column rectangles */
1650     if (infoPtr->colRectsDirty)
1651     {
1652         COLUMN_INFO *info;
1653         LISTVIEW_INFO *Ptr = (LISTVIEW_INFO*)infoPtr;
1654         INT i;
1655 
1656         for (i = 0; i < DPA_GetPtrCount(infoPtr->hdpaColumns); i++) {
1657             info = DPA_GetPtr(infoPtr->hdpaColumns, i);
1658             SendMessageW(infoPtr->hwndHeader, HDM_GETITEMRECT, i, (LPARAM)&info->rcHeader);
1659         }
1660         Ptr->colRectsDirty = FALSE;
1661     }
1662 
1663     return DPA_GetPtr(infoPtr->hdpaColumns, nSubItem);
1664 }
1665 
1666 static INT LISTVIEW_CreateHeader(LISTVIEW_INFO *infoPtr)
1667 {
1668     DWORD dFlags = WS_CHILD | HDS_HORZ | HDS_FULLDRAG | HDS_DRAGDROP;
1669     HINSTANCE hInst;
1670 
1671     if (infoPtr->hwndHeader) return 0;
1672 
1673     TRACE("Creating header for list %p\n", infoPtr->hwndSelf);
1674 
1675     /* setup creation flags */
1676     dFlags |= (LVS_NOSORTHEADER & infoPtr->dwStyle) ? 0 : HDS_BUTTONS;
1677     dFlags |= (LVS_NOCOLUMNHEADER & infoPtr->dwStyle) ? HDS_HIDDEN : 0;
1678 
1679     hInst = (HINSTANCE)GetWindowLongPtrW(infoPtr->hwndSelf, GWLP_HINSTANCE);
1680 
1681     /* create header */
1682     infoPtr->hwndHeader = CreateWindowW(WC_HEADERW, NULL, dFlags,
1683       0, 0, 0, 0, infoPtr->hwndSelf, NULL, hInst, NULL);
1684     if (!infoPtr->hwndHeader) return -1;
1685 
1686     /* set header unicode format */
1687     SendMessageW(infoPtr->hwndHeader, HDM_SETUNICODEFORMAT, TRUE, 0);
1688 
1689     /* set header font */
1690     SendMessageW(infoPtr->hwndHeader, WM_SETFONT, (WPARAM)infoPtr->hFont, TRUE);
1691 
1692     /* set header image list */
1693     if (infoPtr->himlSmall)
1694         SendMessageW(infoPtr->hwndHeader, HDM_SETIMAGELIST, 0, (LPARAM)infoPtr->himlSmall);
1695 
1696     LISTVIEW_UpdateSize(infoPtr);
1697 
1698     return 0;
1699 }
1700 
1701 static inline void LISTVIEW_GetHeaderRect(const LISTVIEW_INFO *infoPtr, INT nSubItem, LPRECT lprc)
1702 {
1703     *lprc = LISTVIEW_GetColumnInfo(infoPtr, nSubItem)->rcHeader;
1704 }
1705 
1706 static inline BOOL LISTVIEW_IsHeaderEnabled(const LISTVIEW_INFO *infoPtr)
1707 {
1708     return (infoPtr->uView == LV_VIEW_DETAILS ||
1709             infoPtr->dwLvExStyle & LVS_EX_HEADERINALLVIEWS) &&
1710           !(infoPtr->dwStyle & LVS_NOCOLUMNHEADER);
1711 }
1712 
1713 static inline BOOL LISTVIEW_GetItemW(const LISTVIEW_INFO *infoPtr, LPLVITEMW lpLVItem)
1714 {
1715     return LISTVIEW_GetItemT(infoPtr, lpLVItem, TRUE);
1716 }
1717 
1718 /* used to handle collapse main item column case */
1719 static inline BOOL LISTVIEW_DrawFocusRect(const LISTVIEW_INFO *infoPtr, HDC hdc)
1720 {
1721 #ifdef __REACTOS__
1722     BOOL Ret = FALSE;
1723 
1724     if (infoPtr->rcFocus.left < infoPtr->rcFocus.right)
1725     {
1726         DWORD dwOldBkColor, dwOldTextColor;
1727 
1728         dwOldBkColor = SetBkColor(hdc, RGB(255, 255, 255));
1729         dwOldTextColor = SetBkColor(hdc, RGB(0, 0, 0));
1730         Ret = DrawFocusRect(hdc, &infoPtr->rcFocus);
1731         SetBkColor(hdc, dwOldBkColor);
1732         SetBkColor(hdc, dwOldTextColor);
1733     }
1734     return Ret;
1735 #else
1736     return (infoPtr->rcFocus.left < infoPtr->rcFocus.right) ?
1737             DrawFocusRect(hdc, &infoPtr->rcFocus) : FALSE;
1738 #endif
1739 }
1740 
1741 /* Listview invalidation functions: use _only_ these functions to invalidate */
1742 
1743 static inline BOOL is_redrawing(const LISTVIEW_INFO *infoPtr)
1744 {
1745     return infoPtr->redraw;
1746 }
1747 
1748 static inline void LISTVIEW_InvalidateRect(const LISTVIEW_INFO *infoPtr, const RECT* rect)
1749 {
1750     if(!is_redrawing(infoPtr)) return;
1751     TRACE(" invalidating rect=%s\n", wine_dbgstr_rect(rect));
1752     InvalidateRect(infoPtr->hwndSelf, rect, TRUE);
1753 }
1754 
1755 static inline void LISTVIEW_InvalidateItem(const LISTVIEW_INFO *infoPtr, INT nItem)
1756 {
1757     RECT rcBox;
1758 
1759     if (!is_redrawing(infoPtr) || nItem < 0 || nItem >= infoPtr->nItemCount)
1760         return;
1761 
1762     LISTVIEW_GetItemBox(infoPtr, nItem, &rcBox);
1763     LISTVIEW_InvalidateRect(infoPtr, &rcBox);
1764 }
1765 
1766 static inline void LISTVIEW_InvalidateSubItem(const LISTVIEW_INFO *infoPtr, INT nItem, INT nSubItem)
1767 {
1768     POINT Origin, Position;
1769     RECT rcBox;
1770 
1771     if(!is_redrawing(infoPtr)) return;
1772     assert (infoPtr->uView == LV_VIEW_DETAILS);
1773     LISTVIEW_GetOrigin(infoPtr, &Origin);
1774     LISTVIEW_GetItemOrigin(infoPtr, nItem, &Position);
1775     LISTVIEW_GetHeaderRect(infoPtr, nSubItem, &rcBox);
1776     rcBox.top = 0;
1777     rcBox.bottom = infoPtr->nItemHeight;
1778     OffsetRect(&rcBox, Origin.x, Origin.y + Position.y);
1779     LISTVIEW_InvalidateRect(infoPtr, &rcBox);
1780 }
1781 
1782 static inline void LISTVIEW_InvalidateList(const LISTVIEW_INFO *infoPtr)
1783 {
1784     LISTVIEW_InvalidateRect(infoPtr, NULL);
1785 }
1786 
1787 static inline void LISTVIEW_InvalidateColumn(const LISTVIEW_INFO *infoPtr, INT nColumn)
1788 {
1789     RECT rcCol;
1790 
1791     if(!is_redrawing(infoPtr)) return;
1792     LISTVIEW_GetHeaderRect(infoPtr, nColumn, &rcCol);
1793     rcCol.top = infoPtr->rcList.top;
1794     rcCol.bottom = infoPtr->rcList.bottom;
1795     LISTVIEW_InvalidateRect(infoPtr, &rcCol);
1796 }
1797 
1798 /***
1799  * DESCRIPTION:
1800  * Retrieves the number of items that can fit vertically in the client area.
1801  *
1802  * PARAMETER(S):
1803  * [I] infoPtr : valid pointer to the listview structure
1804  *
1805  * RETURN:
1806  * Number of items per row.
1807  */
1808 static inline INT LISTVIEW_GetCountPerRow(const LISTVIEW_INFO *infoPtr)
1809 {
1810     INT nListWidth = infoPtr->rcList.right - infoPtr->rcList.left;
1811 
1812     return max(nListWidth/(infoPtr->nItemWidth ? infoPtr->nItemWidth : 1), 1);
1813 }
1814 
1815 /***
1816  * DESCRIPTION:
1817  * Retrieves the number of items that can fit horizontally in the client
1818  * area.
1819  *
1820  * PARAMETER(S):
1821  * [I] infoPtr : valid pointer to the listview structure
1822  *
1823  * RETURN:
1824  * Number of items per column.
1825  */
1826 static inline INT LISTVIEW_GetCountPerColumn(const LISTVIEW_INFO *infoPtr)
1827 {
1828     INT nListHeight = infoPtr->rcList.bottom - infoPtr->rcList.top;
1829 
1830     return infoPtr->nItemHeight ? max(nListHeight / infoPtr->nItemHeight, 1) : 0;
1831 }
1832 
1833 
1834 /*************************************************************************
1835  *		LISTVIEW_ProcessLetterKeys
1836  *
1837  *  Processes keyboard messages generated by pressing the letter keys
1838  *  on the keyboard.
1839  *  What this does is perform a case insensitive search from the
1840  *  current position with the following quirks:
1841  *  - If two chars or more are pressed in quick succession we search
1842  *    for the corresponding string (e.g. 'abc').
1843  *  - If there is a delay we wipe away the current search string and
1844  *    restart with just that char.
1845  *  - If the user keeps pressing the same character, whether slowly or
1846  *    fast, so that the search string is entirely composed of this
1847  *    character ('aaaaa' for instance), then we search for first item
1848  *    that starting with that character.
1849  *  - If the user types the above character in quick succession, then
1850  *    we must also search for the corresponding string ('aaaaa'), and
1851  *    go to that string if there is a match.
1852  *
1853  * PARAMETERS
1854  *   [I] hwnd : handle to the window
1855  *   [I] charCode : the character code, the actual character
1856  *   [I] keyData : key data
1857  *
1858  * RETURNS
1859  *
1860  *  Zero.
1861  *
1862  * BUGS
1863  *
1864  *  - The current implementation has a list of characters it will
1865  *    accept and it ignores everything else. In particular it will
1866  *    ignore accentuated characters which seems to match what
1867  *    Windows does. But I'm not sure it makes sense to follow
1868  *    Windows there.
1869  *  - We don't sound a beep when the search fails.
1870  *
1871  * SEE ALSO
1872  *
1873  *  TREEVIEW_ProcessLetterKeys
1874  */
1875 static INT LISTVIEW_ProcessLetterKeys(LISTVIEW_INFO *infoPtr, WPARAM charCode, LPARAM keyData)
1876 {
1877     WCHAR buffer[MAX_PATH];
1878     DWORD prevTime;
1879     LVITEMW item;
1880     int startidx;
1881     INT nItem;
1882     INT diff;
1883 
1884     /* simple parameter checking */
1885     if (!charCode || !keyData || infoPtr->nItemCount == 0) return 0;
1886 
1887     /* only allow the valid WM_CHARs through */
1888     if (!iswalnum(charCode) &&
1889         charCode != '.' && charCode != '`' && charCode != '!' &&
1890         charCode != '@' && charCode != '#' && charCode != '$' &&
1891         charCode != '%' && charCode != '^' && charCode != '&' &&
1892         charCode != '*' && charCode != '(' && charCode != ')' &&
1893         charCode != '-' && charCode != '_' && charCode != '+' &&
1894         charCode != '=' && charCode != '\\'&& charCode != ']' &&
1895         charCode != '}' && charCode != '[' && charCode != '{' &&
1896         charCode != '/' && charCode != '?' && charCode != '>' &&
1897         charCode != '<' && charCode != ',' && charCode != '~')
1898         return 0;
1899 
1900     /* update the search parameters */
1901     prevTime = infoPtr->lastKeyPressTimestamp;
1902     infoPtr->lastKeyPressTimestamp = GetTickCount();
1903     diff = infoPtr->lastKeyPressTimestamp - prevTime;
1904 
1905     if (diff >= 0 && diff < KEY_DELAY)
1906     {
1907         if (infoPtr->nSearchParamLength < MAX_PATH - 1)
1908             infoPtr->szSearchParam[infoPtr->nSearchParamLength++] = charCode;
1909 
1910         if (infoPtr->charCode != charCode)
1911             infoPtr->charCode = charCode = 0;
1912     }
1913     else
1914     {
1915         infoPtr->charCode = charCode;
1916         infoPtr->szSearchParam[0] = charCode;
1917         infoPtr->nSearchParamLength = 1;
1918     }
1919 
1920     /* should start from next after focused item, so next item that matches
1921        will be selected, if there isn't any and focused matches it will be selected
1922        on second search stage from beginning of the list */
1923     if (infoPtr->nFocusedItem >= 0 && infoPtr->nItemCount > 1)
1924     {
1925         /* with some accumulated search data available start with current focus, otherwise
1926            it's excluded from search */
1927         startidx = infoPtr->nSearchParamLength > 1 ? infoPtr->nFocusedItem : infoPtr->nFocusedItem + 1;
1928         if (startidx == infoPtr->nItemCount) startidx = 0;
1929     }
1930     else
1931         startidx = 0;
1932 
1933     /* let application handle this for virtual listview */
1934     if (infoPtr->dwStyle & LVS_OWNERDATA)
1935     {
1936         NMLVFINDITEMW nmlv;
1937 
1938         memset(&nmlv.lvfi, 0, sizeof(nmlv.lvfi));
1939         nmlv.lvfi.flags = (LVFI_WRAP | LVFI_PARTIAL);
1940         nmlv.lvfi.psz = infoPtr->szSearchParam;
1941         nmlv.iStart = startidx;
1942 
1943         infoPtr->szSearchParam[infoPtr->nSearchParamLength] = 0;
1944 
1945         nItem = notify_hdr(infoPtr, LVN_ODFINDITEMW, (LPNMHDR)&nmlv.hdr);
1946     }
1947     else
1948     {
1949         int i = startidx, endidx;
1950 
1951         /* and search from the current position */
1952         nItem = -1;
1953         endidx = infoPtr->nItemCount;
1954 
1955         /* first search in [startidx, endidx), on failure continue in [0, startidx) */
1956         while (1)
1957         {
1958             /* start from first item if not found with >= startidx */
1959             if (i == infoPtr->nItemCount && startidx > 0)
1960             {
1961                 endidx = startidx;
1962                 startidx = 0;
1963             }
1964 
1965             for (i = startidx; i < endidx; i++)
1966             {
1967                 /* retrieve text */
1968                 item.mask = LVIF_TEXT;
1969                 item.iItem = i;
1970                 item.iSubItem = 0;
1971                 item.pszText = buffer;
1972                 item.cchTextMax = MAX_PATH;
1973                 if (!LISTVIEW_GetItemW(infoPtr, &item)) return 0;
1974 
1975                 if (!lstrncmpiW(item.pszText, infoPtr->szSearchParam, infoPtr->nSearchParamLength))
1976                 {
1977                     nItem = i;
1978                     break;
1979                 }
1980                 /* this is used to find first char match when search string is not available yet,
1981                    otherwise every WM_CHAR will search to next item by first char, ignoring that we're
1982                    already waiting for user to complete a string */
1983                 else if (nItem == -1 && infoPtr->nSearchParamLength == 1 && !lstrncmpiW(item.pszText, infoPtr->szSearchParam, 1))
1984                 {
1985                     /* this would work but we must keep looking for a longer match */
1986                     nItem = i;
1987                 }
1988             }
1989 
1990             if ( nItem != -1 || /* found something */
1991                  endidx != infoPtr->nItemCount || /* second search done */
1992                 (startidx == 0 && endidx == infoPtr->nItemCount) /* full range for first search */ )
1993                 break;
1994         };
1995     }
1996 
1997     if (nItem != -1)
1998         LISTVIEW_KeySelection(infoPtr, nItem, FALSE);
1999 
2000     return 0;
2001 }
2002 
2003 /*************************************************************************
2004  * LISTVIEW_UpdateHeaderSize [Internal]
2005  *
2006  * Function to resize the header control
2007  *
2008  * PARAMS
2009  * [I]  hwnd : handle to a window
2010  * [I]  nNewScrollPos : scroll pos to set
2011  *
2012  * RETURNS
2013  * None.
2014  */
2015 static void LISTVIEW_UpdateHeaderSize(const LISTVIEW_INFO *infoPtr, INT nNewScrollPos)
2016 {
2017     RECT winRect;
2018     POINT point[2];
2019 
2020     TRACE("nNewScrollPos=%d\n", nNewScrollPos);
2021 
2022     if (!infoPtr->hwndHeader)  return;
2023 
2024     GetWindowRect(infoPtr->hwndHeader, &winRect);
2025     point[0].x = winRect.left;
2026     point[0].y = winRect.top;
2027     point[1].x = winRect.right;
2028     point[1].y = winRect.bottom;
2029 
2030     MapWindowPoints(HWND_DESKTOP, infoPtr->hwndSelf, point, 2);
2031     point[0].x = -nNewScrollPos;
2032     point[1].x += nNewScrollPos;
2033 
2034     SetWindowPos(infoPtr->hwndHeader,0,
2035         point[0].x,point[0].y,point[1].x,point[1].y,
2036         (infoPtr->dwStyle & LVS_NOCOLUMNHEADER) ? SWP_HIDEWINDOW : SWP_SHOWWINDOW |
2037         SWP_NOZORDER | SWP_NOACTIVATE);
2038 }
2039 
2040 static INT LISTVIEW_UpdateHScroll(LISTVIEW_INFO *infoPtr)
2041 {
2042     SCROLLINFO horzInfo;
2043     INT dx;
2044 
2045     ZeroMemory(&horzInfo, sizeof(SCROLLINFO));
2046     horzInfo.cbSize = sizeof(SCROLLINFO);
2047     horzInfo.nPage = infoPtr->rcList.right - infoPtr->rcList.left;
2048 
2049     /* for now, we'll set info.nMax to the _count_, and adjust it later */
2050     if (infoPtr->uView == LV_VIEW_LIST)
2051     {
2052 	INT nPerCol = LISTVIEW_GetCountPerColumn(infoPtr);
2053 	horzInfo.nMax = (infoPtr->nItemCount + nPerCol - 1) / nPerCol;
2054 
2055 	/* scroll by at least one column per page */
2056 	if(horzInfo.nPage < infoPtr->nItemWidth)
2057 		horzInfo.nPage = infoPtr->nItemWidth;
2058 
2059 	if (infoPtr->nItemWidth)
2060 	    horzInfo.nPage /= infoPtr->nItemWidth;
2061     }
2062     else if (infoPtr->uView == LV_VIEW_DETAILS)
2063     {
2064 	horzInfo.nMax = infoPtr->nItemWidth;
2065     }
2066     else /* LV_VIEW_ICON, or LV_VIEW_SMALLICON */
2067     {
2068 	RECT rcView;
2069 
2070 	if (LISTVIEW_GetViewRect(infoPtr, &rcView)) horzInfo.nMax = rcView.right - rcView.left;
2071     }
2072 
2073     if (LISTVIEW_IsHeaderEnabled(infoPtr))
2074     {
2075 	if (DPA_GetPtrCount(infoPtr->hdpaColumns))
2076 	{
2077 	    RECT rcHeader;
2078 	    INT index;
2079 
2080 	    index = SendMessageW(infoPtr->hwndHeader, HDM_ORDERTOINDEX,
2081                                  DPA_GetPtrCount(infoPtr->hdpaColumns) - 1, 0);
2082 
2083 	    LISTVIEW_GetHeaderRect(infoPtr, index, &rcHeader);
2084 	    horzInfo.nMax = rcHeader.right;
2085 	    TRACE("horzInfo.nMax=%d\n", horzInfo.nMax);
2086 	}
2087     }
2088 
2089     horzInfo.fMask = SIF_RANGE | SIF_PAGE;
2090     horzInfo.nMax = max(horzInfo.nMax - 1, 0);
2091 #ifdef __REACTOS__ /* CORE-16466 part 1 of 4 */
2092     horzInfo.nMax = (horzInfo.nPage == 0 ? 0 : horzInfo.nMax);
2093 #endif
2094     dx = GetScrollPos(infoPtr->hwndSelf, SB_HORZ);
2095     dx -= SetScrollInfo(infoPtr->hwndSelf, SB_HORZ, &horzInfo, TRUE);
2096     TRACE("horzInfo=%s\n", debugscrollinfo(&horzInfo));
2097 
2098     /* Update the Header Control */
2099     if (infoPtr->hwndHeader)
2100     {
2101 	horzInfo.fMask = SIF_POS;
2102 	GetScrollInfo(infoPtr->hwndSelf, SB_HORZ, &horzInfo);
2103 	LISTVIEW_UpdateHeaderSize(infoPtr, horzInfo.nPos);
2104     }
2105 
2106     LISTVIEW_UpdateSize(infoPtr);
2107     return dx;
2108 }
2109 
2110 static INT LISTVIEW_UpdateVScroll(LISTVIEW_INFO *infoPtr)
2111 {
2112     SCROLLINFO vertInfo;
2113     INT dy;
2114 
2115     ZeroMemory(&vertInfo, sizeof(SCROLLINFO));
2116     vertInfo.cbSize = sizeof(SCROLLINFO);
2117 #ifdef __REACTOS__ /* CORE-16466 part 2 of 4 */
2118     vertInfo.nPage = max(0, infoPtr->rcList.bottom - infoPtr->rcList.top);
2119 #else
2120     vertInfo.nPage = infoPtr->rcList.bottom - infoPtr->rcList.top;
2121 #endif
2122 
2123     if (infoPtr->uView == LV_VIEW_DETAILS)
2124     {
2125 #ifdef __REACTOS__ /* CORE-16466 part 3a of 4 */
2126       if (vertInfo.nPage != 0)
2127       {
2128 #endif
2129 	vertInfo.nMax = infoPtr->nItemCount;
2130 
2131 	/* scroll by at least one page */
2132 	if(vertInfo.nPage < infoPtr->nItemHeight)
2133 	  vertInfo.nPage = infoPtr->nItemHeight;
2134 
2135         if (infoPtr->nItemHeight > 0)
2136             vertInfo.nPage /= infoPtr->nItemHeight;
2137 #ifdef __REACTOS__ /* CORE-16466 part 3b of 4 */
2138       }
2139 #endif
2140     }
2141     else if (infoPtr->uView != LV_VIEW_LIST) /* LV_VIEW_ICON, or LV_VIEW_SMALLICON */
2142     {
2143 	RECT rcView;
2144 
2145 	if (LISTVIEW_GetViewRect(infoPtr, &rcView)) vertInfo.nMax = rcView.bottom - rcView.top;
2146     }
2147 
2148     vertInfo.fMask = SIF_RANGE | SIF_PAGE;
2149     vertInfo.nMax = max(vertInfo.nMax - 1, 0);
2150 #ifdef __REACTOS__ /* CORE-16466 part 4 of 4 */
2151     vertInfo.nMax = (vertInfo.nPage == 0 ? 0 : vertInfo.nMax);
2152 #endif
2153     dy = GetScrollPos(infoPtr->hwndSelf, SB_VERT);
2154     dy -= SetScrollInfo(infoPtr->hwndSelf, SB_VERT, &vertInfo, TRUE);
2155     TRACE("vertInfo=%s\n", debugscrollinfo(&vertInfo));
2156 
2157     LISTVIEW_UpdateSize(infoPtr);
2158     return dy;
2159 }
2160 
2161 /***
2162  * DESCRIPTION:
2163  * Update the scrollbars. This function should be called whenever
2164  * the content, size or view changes.
2165  *
2166  * PARAMETER(S):
2167  * [I] infoPtr : valid pointer to the listview structure
2168  *
2169  * RETURN:
2170  * None
2171  */
2172 static void LISTVIEW_UpdateScroll(LISTVIEW_INFO *infoPtr)
2173 {
2174     INT dx, dy, pass;
2175 
2176     if ((infoPtr->dwStyle & LVS_NOSCROLL) || !is_redrawing(infoPtr)) return;
2177 
2178     /* Setting the horizontal scroll can change the listview size
2179      * (and potentially everything else) so we need to recompute
2180      * everything again for the vertical scroll and vice-versa
2181      */
2182     for (dx = 0, dy = 0, pass = 0; pass <= 1; pass++)
2183     {
2184         dx += LISTVIEW_UpdateHScroll(infoPtr);
2185         dy += LISTVIEW_UpdateVScroll(infoPtr);
2186     }
2187 
2188     /* Change of the range may have changed the scroll pos. If so move the content */
2189     if (dx != 0 || dy != 0)
2190     {
2191         RECT listRect;
2192         listRect = infoPtr->rcList;
2193         ScrollWindowEx(infoPtr->hwndSelf, dx, dy, &listRect, &listRect, 0, 0,
2194             SW_ERASE | SW_INVALIDATE);
2195     }
2196 }
2197 
2198 
2199 /***
2200  * DESCRIPTION:
2201  * Shows/hides the focus rectangle.
2202  *
2203  * PARAMETER(S):
2204  * [I] infoPtr : valid pointer to the listview structure
2205  * [I] fShow : TRUE to show the focus, FALSE to hide it.
2206  *
2207  * RETURN:
2208  * None
2209  */
2210 static void LISTVIEW_ShowFocusRect(const LISTVIEW_INFO *infoPtr, BOOL fShow)
2211 {
2212     HDC hdc;
2213 
2214     TRACE("fShow=%d, nItem=%d\n", fShow, infoPtr->nFocusedItem);
2215 
2216     if (infoPtr->nFocusedItem < 0) return;
2217 
2218     /* we need some gymnastics in ICON mode to handle large items */
2219     if (infoPtr->uView == LV_VIEW_ICON)
2220     {
2221 	RECT rcBox;
2222 
2223 	LISTVIEW_GetItemBox(infoPtr, infoPtr->nFocusedItem, &rcBox);
2224 	if ((rcBox.bottom - rcBox.top) > infoPtr->nItemHeight)
2225 	{
2226 	    LISTVIEW_InvalidateRect(infoPtr, &rcBox);
2227 	    return;
2228 	}
2229     }
2230 
2231     if (!(hdc = GetDC(infoPtr->hwndSelf))) return;
2232 
2233     /* for some reason, owner draw should work only in report mode */
2234     if ((infoPtr->dwStyle & LVS_OWNERDRAWFIXED) && (infoPtr->uView == LV_VIEW_DETAILS))
2235     {
2236 	DRAWITEMSTRUCT dis;
2237 	LVITEMW item;
2238 
2239 	HFONT hFont = infoPtr->hFont ? infoPtr->hFont : infoPtr->hDefaultFont;
2240 	HFONT hOldFont = SelectObject(hdc, hFont);
2241 
2242         item.iItem = infoPtr->nFocusedItem;
2243 	item.iSubItem = 0;
2244         item.mask = LVIF_PARAM;
2245 	if (!LISTVIEW_GetItemW(infoPtr, &item)) goto done;
2246 
2247 	ZeroMemory(&dis, sizeof(dis));
2248 	dis.CtlType = ODT_LISTVIEW;
2249 	dis.CtlID = (UINT)GetWindowLongPtrW(infoPtr->hwndSelf, GWLP_ID);
2250 	dis.itemID = item.iItem;
2251 	dis.itemAction = ODA_FOCUS;
2252 	if (fShow) dis.itemState |= ODS_FOCUS;
2253 	dis.hwndItem = infoPtr->hwndSelf;
2254 	dis.hDC = hdc;
2255 	LISTVIEW_GetItemBox(infoPtr, dis.itemID, &dis.rcItem);
2256 	dis.itemData = item.lParam;
2257 
2258 	SendMessageW(infoPtr->hwndNotify, WM_DRAWITEM, dis.CtlID, (LPARAM)&dis);
2259 
2260 	SelectObject(hdc, hOldFont);
2261     }
2262     else
2263         LISTVIEW_InvalidateItem(infoPtr, infoPtr->nFocusedItem);
2264 
2265 done:
2266     ReleaseDC(infoPtr->hwndSelf, hdc);
2267 }
2268 
2269 /***
2270  * Invalidates all visible selected items.
2271  */
2272 static void LISTVIEW_InvalidateSelectedItems(const LISTVIEW_INFO *infoPtr)
2273 {
2274     ITERATOR i;
2275 
2276     iterator_frameditems(&i, infoPtr, &infoPtr->rcList);
2277     while(iterator_next(&i))
2278     {
2279 	if (LISTVIEW_GetItemState(infoPtr, i.nItem, LVIS_SELECTED))
2280 	    LISTVIEW_InvalidateItem(infoPtr, i.nItem);
2281     }
2282     iterator_destroy(&i);
2283 }
2284 
2285 
2286 /***
2287  * DESCRIPTION:            [INTERNAL]
2288  * Computes an item's (left,top) corner, relative to rcView.
2289  * That is, the position has NOT been made relative to the Origin.
2290  * This is deliberate, to avoid computing the Origin over, and
2291  * over again, when this function is called in a loop. Instead,
2292  * one can factor the computation of the Origin before the loop,
2293  * and offset the value returned by this function, on every iteration.
2294  *
2295  * PARAMETER(S):
2296  * [I] infoPtr : valid pointer to the listview structure
2297  * [I] nItem  : item number
2298  * [O] lpptOrig : item top, left corner
2299  *
2300  * RETURN:
2301  *   None.
2302  */
2303 static void LISTVIEW_GetItemOrigin(const LISTVIEW_INFO *infoPtr, INT nItem, LPPOINT lpptPosition)
2304 {
2305     assert(nItem >= 0 && nItem < infoPtr->nItemCount);
2306 
2307     if ((infoPtr->uView == LV_VIEW_SMALLICON) || (infoPtr->uView == LV_VIEW_ICON))
2308     {
2309 	lpptPosition->x = (LONG_PTR)DPA_GetPtr(infoPtr->hdpaPosX, nItem);
2310 	lpptPosition->y = (LONG_PTR)DPA_GetPtr(infoPtr->hdpaPosY, nItem);
2311     }
2312     else if (infoPtr->uView == LV_VIEW_LIST)
2313     {
2314         INT nCountPerColumn = LISTVIEW_GetCountPerColumn(infoPtr);
2315 	lpptPosition->x = nItem / nCountPerColumn * infoPtr->nItemWidth;
2316 	lpptPosition->y = nItem % nCountPerColumn * infoPtr->nItemHeight;
2317     }
2318     else /* LV_VIEW_DETAILS */
2319     {
2320 	lpptPosition->x = REPORT_MARGINX;
2321 	/* item is always at zero indexed column */
2322 	if (DPA_GetPtrCount(infoPtr->hdpaColumns) > 0)
2323 	    lpptPosition->x += LISTVIEW_GetColumnInfo(infoPtr, 0)->rcHeader.left;
2324 	lpptPosition->y = nItem * infoPtr->nItemHeight;
2325     }
2326 }
2327 
2328 /***
2329  * DESCRIPTION:            [INTERNAL]
2330  * Compute the rectangles of an item.  This is to localize all
2331  * the computations in one place. If you are not interested in some
2332  * of these values, simply pass in a NULL -- the function is smart
2333  * enough to compute only what's necessary. The function computes
2334  * the standard rectangles (BOUNDS, ICON, LABEL) plus a non-standard
2335  * one, the BOX rectangle. This rectangle is very cheap to compute,
2336  * and is guaranteed to contain all the other rectangles. Computing
2337  * the ICON rect is also cheap, but all the others are potentially
2338  * expensive. This gives an easy and effective optimization when
2339  * searching (like point inclusion, or rectangle intersection):
2340  * first test against the BOX, and if TRUE, test against the desired
2341  * rectangle.
2342  * If the function does not have all the necessary information
2343  * to computed the requested rectangles, will crash with a
2344  * failed assertion. This is done so we catch all programming
2345  * errors, given that the function is called only from our code.
2346  *
2347  * We have the following 'special' meanings for a few fields:
2348  *   * If LVIS_FOCUSED is set, we assume the item has the focus
2349  *     This is important in ICON mode, where it might get a larger
2350  *     then usual rectangle
2351  *
2352  * Please note that subitem support works only in REPORT mode.
2353  *
2354  * PARAMETER(S):
2355  * [I] infoPtr : valid pointer to the listview structure
2356  * [I] lpLVItem : item to compute the measures for
2357  * [O] lprcBox : ptr to Box rectangle
2358  *                Same as LVM_GETITEMRECT with LVIR_BOUNDS
2359  * [0] lprcSelectBox : ptr to select box rectangle
2360  *  		  Same as LVM_GETITEMRECT with LVIR_SELECTEDBOUNDS
2361  * [O] lprcIcon : ptr to Icon rectangle
2362  *                Same as LVM_GETITEMRECT with LVIR_ICON
2363  * [O] lprcStateIcon: ptr to State Icon rectangle
2364  * [O] lprcLabel : ptr to Label rectangle
2365  *                Same as LVM_GETITEMRECT with LVIR_LABEL
2366  *
2367  * RETURN:
2368  *   None.
2369  */
2370 static void LISTVIEW_GetItemMetrics(const LISTVIEW_INFO *infoPtr, const LVITEMW *lpLVItem,
2371 				    LPRECT lprcBox, LPRECT lprcSelectBox,
2372 				    LPRECT lprcIcon, LPRECT lprcStateIcon, LPRECT lprcLabel)
2373 {
2374     BOOL doSelectBox = FALSE, doIcon = FALSE, doLabel = FALSE, oversizedBox = FALSE;
2375     RECT Box, SelectBox, Icon, Label;
2376     COLUMN_INFO *lpColumnInfo = NULL;
2377     SIZE labelSize = { 0, 0 };
2378 
2379     TRACE("(lpLVItem=%s)\n", debuglvitem_t(lpLVItem, TRUE));
2380 
2381     /* Be smart and try to figure out the minimum we have to do */
2382     if (lpLVItem->iSubItem) assert(infoPtr->uView == LV_VIEW_DETAILS);
2383     if (infoPtr->uView == LV_VIEW_ICON && (lprcBox || lprcLabel))
2384     {
2385 	assert((lpLVItem->mask & LVIF_STATE) && (lpLVItem->stateMask & LVIS_FOCUSED));
2386 	if (lpLVItem->state & LVIS_FOCUSED) oversizedBox = doLabel = TRUE;
2387     }
2388     if (lprcSelectBox) doSelectBox = TRUE;
2389     if (lprcLabel) doLabel = TRUE;
2390     if (doLabel || lprcIcon || lprcStateIcon) doIcon = TRUE;
2391     if (doSelectBox)
2392     {
2393         doIcon = TRUE;
2394         doLabel = TRUE;
2395     }
2396 
2397     /************************************************************/
2398     /* compute the box rectangle (it should be cheap to do)     */
2399     /************************************************************/
2400     if (lpLVItem->iSubItem || infoPtr->uView == LV_VIEW_DETAILS)
2401 	lpColumnInfo = LISTVIEW_GetColumnInfo(infoPtr, lpLVItem->iSubItem);
2402 
2403     if (lpLVItem->iSubItem)
2404     {
2405 	Box = lpColumnInfo->rcHeader;
2406     }
2407     else
2408     {
2409 	Box.left = 0;
2410 	Box.right = infoPtr->nItemWidth;
2411     }
2412     Box.top = 0;
2413     Box.bottom = infoPtr->nItemHeight;
2414 
2415     /******************************************************************/
2416     /* compute ICON bounding box (ala LVM_GETITEMRECT) and STATEICON  */
2417     /******************************************************************/
2418     if (doIcon)
2419     {
2420 	LONG state_width = 0;
2421 
2422 	if (infoPtr->himlState && lpLVItem->iSubItem == 0)
2423 	    state_width = infoPtr->iconStateSize.cx;
2424 
2425 	if (infoPtr->uView == LV_VIEW_ICON)
2426 	{
2427 	    Icon.left   = Box.left + state_width;
2428 	    if (infoPtr->himlNormal)
2429 		Icon.left += (infoPtr->nItemWidth - infoPtr->iconSize.cx - state_width) / 2;
2430 	    Icon.top    = Box.top + ICON_TOP_PADDING;
2431 	    Icon.right  = Icon.left;
2432 	    Icon.bottom = Icon.top;
2433 	    if (infoPtr->himlNormal)
2434 	    {
2435 		Icon.right  += infoPtr->iconSize.cx;
2436 		Icon.bottom += infoPtr->iconSize.cy;
2437 	    }
2438 	}
2439 	else /* LV_VIEW_SMALLICON, LV_VIEW_LIST or LV_VIEW_DETAILS */
2440 	{
2441 	    Icon.left   = Box.left + state_width;
2442 
2443 	    if (infoPtr->uView == LV_VIEW_DETAILS && lpLVItem->iSubItem == 0)
2444 	    {
2445 		/* we need the indent in report mode */
2446 		assert(lpLVItem->mask & LVIF_INDENT);
2447 		Icon.left += infoPtr->iconSize.cx * lpLVItem->iIndent + REPORT_MARGINX;
2448 	    }
2449 
2450 	    Icon.top    = Box.top;
2451 	    Icon.right  = Icon.left;
2452 	    if (infoPtr->himlSmall &&
2453                 (!lpColumnInfo || lpLVItem->iSubItem == 0 ||
2454                  ((infoPtr->dwLvExStyle & LVS_EX_SUBITEMIMAGES) && lpLVItem->iImage != I_IMAGECALLBACK)))
2455 		Icon.right += infoPtr->iconSize.cx;
2456 	    Icon.bottom = Icon.top + infoPtr->iconSize.cy;
2457 	}
2458 	if(lprcIcon) *lprcIcon = Icon;
2459 	TRACE("    - icon=%s\n", wine_dbgstr_rect(&Icon));
2460 
2461         /* TODO: is this correct? */
2462         if (lprcStateIcon)
2463         {
2464             lprcStateIcon->left = Icon.left - state_width;
2465             lprcStateIcon->right = Icon.left;
2466             lprcStateIcon->top = Icon.top;
2467             lprcStateIcon->bottom = lprcStateIcon->top + infoPtr->iconSize.cy;
2468             TRACE("    - state icon=%s\n", wine_dbgstr_rect(lprcStateIcon));
2469         }
2470      }
2471      else Icon.right = 0;
2472 
2473     /************************************************************/
2474     /* compute LABEL bounding box (ala LVM_GETITEMRECT)         */
2475     /************************************************************/
2476     if (doLabel)
2477     {
2478 	/* calculate how far to the right can the label stretch */
2479 	Label.right = Box.right;
2480 	if (infoPtr->uView == LV_VIEW_DETAILS)
2481 	{
2482 	    if (lpLVItem->iSubItem == 0)
2483 	    {
2484 		/* we need a zero based rect here */
2485 		Label = lpColumnInfo->rcHeader;
2486 		OffsetRect(&Label, -Label.left, 0);
2487 	    }
2488 	}
2489 
2490 	if (lpLVItem->iSubItem || ((infoPtr->dwStyle & LVS_OWNERDRAWFIXED) && infoPtr->uView == LV_VIEW_DETAILS))
2491 	{
2492 	   labelSize.cx = infoPtr->nItemWidth;
2493 	   labelSize.cy = infoPtr->nItemHeight;
2494 	   goto calc_label;
2495 	}
2496 
2497 	/* we need the text in non owner draw mode */
2498 	assert(lpLVItem->mask & LVIF_TEXT);
2499 	if (is_text(lpLVItem->pszText))
2500         {
2501     	    HFONT hFont = infoPtr->hFont ? infoPtr->hFont : infoPtr->hDefaultFont;
2502     	    HDC hdc = GetDC(infoPtr->hwndSelf);
2503     	    HFONT hOldFont = SelectObject(hdc, hFont);
2504 	    UINT uFormat;
2505 	    RECT rcText;
2506 
2507 	    /* compute rough rectangle where the label will go */
2508 	    SetRectEmpty(&rcText);
2509 	    rcText.right = infoPtr->nItemWidth - TRAILING_LABEL_PADDING;
2510 	    rcText.bottom = infoPtr->nItemHeight;
2511 	    if (infoPtr->uView == LV_VIEW_ICON)
2512 		rcText.bottom -= ICON_TOP_PADDING + infoPtr->iconSize.cy + ICON_BOTTOM_PADDING;
2513 
2514 	    /* now figure out the flags */
2515 	    if (infoPtr->uView == LV_VIEW_ICON)
2516 		uFormat = oversizedBox ? LV_FL_DT_FLAGS : LV_ML_DT_FLAGS;
2517 	    else
2518 		uFormat = LV_SL_DT_FLAGS;
2519 
2520     	    DrawTextW (hdc, lpLVItem->pszText, -1, &rcText, uFormat | DT_CALCRECT);
2521 
2522 	    if (rcText.right != rcText.left)
2523 	        labelSize.cx = min(rcText.right - rcText.left + TRAILING_LABEL_PADDING, infoPtr->nItemWidth);
2524 
2525 	    labelSize.cy = rcText.bottom - rcText.top;
2526 
2527     	    SelectObject(hdc, hOldFont);
2528     	    ReleaseDC(infoPtr->hwndSelf, hdc);
2529 	}
2530 
2531 calc_label:
2532 	if (infoPtr->uView == LV_VIEW_ICON)
2533 	{
2534 	    Label.left = Box.left + (infoPtr->nItemWidth - labelSize.cx) / 2;
2535 	    Label.top  = Box.top + ICON_TOP_PADDING_HITABLE +
2536 		         infoPtr->iconSize.cy + ICON_BOTTOM_PADDING;
2537 	    Label.right = Label.left + labelSize.cx;
2538 	    Label.bottom = Label.top + infoPtr->nItemHeight;
2539 	    if (!oversizedBox && labelSize.cy > infoPtr->ntmHeight)
2540 	    {
2541 		labelSize.cy = min(Box.bottom - Label.top, labelSize.cy);
2542 		labelSize.cy /= infoPtr->ntmHeight;
2543 		labelSize.cy = max(labelSize.cy, 1);
2544 		labelSize.cy *= infoPtr->ntmHeight;
2545 	     }
2546 	     Label.bottom = Label.top + labelSize.cy + HEIGHT_PADDING;
2547 	}
2548 	else if (infoPtr->uView == LV_VIEW_DETAILS)
2549 	{
2550 	    Label.left = Icon.right;
2551 	    Label.top = Box.top;
2552 	    Label.right = lpLVItem->iSubItem ? lpColumnInfo->rcHeader.right :
2553 			  lpColumnInfo->rcHeader.right - lpColumnInfo->rcHeader.left;
2554 	    Label.bottom = Label.top + infoPtr->nItemHeight;
2555 	}
2556 	else /* LV_VIEW_SMALLICON or LV_VIEW_LIST */
2557 	{
2558 	    Label.left = Icon.right;
2559 	    Label.top = Box.top;
2560 	    Label.right = min(Label.left + labelSize.cx, Label.right);
2561 	    Label.bottom = Label.top + infoPtr->nItemHeight;
2562 	}
2563 
2564 	if (lprcLabel) *lprcLabel = Label;
2565 	TRACE("    - label=%s\n", wine_dbgstr_rect(&Label));
2566     }
2567 
2568     /************************************************************/
2569     /* compute SELECT bounding box                              */
2570     /************************************************************/
2571     if (doSelectBox)
2572     {
2573 	if (infoPtr->uView == LV_VIEW_DETAILS)
2574 	{
2575 	    SelectBox.left = Icon.left;
2576 	    SelectBox.top = Box.top;
2577 	    SelectBox.bottom = Box.bottom;
2578 
2579 	    if (labelSize.cx)
2580 	        SelectBox.right = min(Label.left + labelSize.cx, Label.right);
2581 	    else
2582 	        SelectBox.right = min(Label.left + MAX_EMPTYTEXT_SELECT_WIDTH, Label.right);
2583 	}
2584 	else
2585 	{
2586 	    UnionRect(&SelectBox, &Icon, &Label);
2587 	}
2588 	if (lprcSelectBox) *lprcSelectBox = SelectBox;
2589 	TRACE("    - select box=%s\n", wine_dbgstr_rect(&SelectBox));
2590     }
2591 
2592     /* Fix the Box if necessary */
2593     if (lprcBox)
2594     {
2595 	if (oversizedBox) UnionRect(lprcBox, &Box, &Label);
2596 	else *lprcBox = Box;
2597     }
2598     TRACE("    - box=%s\n", wine_dbgstr_rect(&Box));
2599 }
2600 
2601 /***
2602  * DESCRIPTION:            [INTERNAL]
2603  *
2604  * PARAMETER(S):
2605  * [I] infoPtr : valid pointer to the listview structure
2606  * [I] nItem : item number
2607  * [O] lprcBox : ptr to Box rectangle
2608  *
2609  * RETURN:
2610  *   None.
2611  */
2612 static void LISTVIEW_GetItemBox(const LISTVIEW_INFO *infoPtr, INT nItem, LPRECT lprcBox)
2613 {
2614     WCHAR szDispText[DISP_TEXT_SIZE] = { '\0' };
2615     POINT Position, Origin;
2616     LVITEMW lvItem;
2617 
2618     LISTVIEW_GetOrigin(infoPtr, &Origin);
2619     LISTVIEW_GetItemOrigin(infoPtr, nItem, &Position);
2620 
2621     /* Be smart and try to figure out the minimum we have to do */
2622     lvItem.mask = 0;
2623     if (infoPtr->uView == LV_VIEW_ICON && infoPtr->bFocus && LISTVIEW_GetItemState(infoPtr, nItem, LVIS_FOCUSED))
2624 	lvItem.mask |= LVIF_TEXT;
2625     lvItem.iItem = nItem;
2626     lvItem.iSubItem = 0;
2627     lvItem.pszText = szDispText;
2628     lvItem.cchTextMax = DISP_TEXT_SIZE;
2629     if (lvItem.mask) LISTVIEW_GetItemW(infoPtr, &lvItem);
2630     if (infoPtr->uView == LV_VIEW_ICON)
2631     {
2632 	lvItem.mask |= LVIF_STATE;
2633 	lvItem.stateMask = LVIS_FOCUSED;
2634 	lvItem.state = (lvItem.mask & LVIF_TEXT ? LVIS_FOCUSED : 0);
2635     }
2636     LISTVIEW_GetItemMetrics(infoPtr, &lvItem, lprcBox, 0, 0, 0, 0);
2637 
2638     if (infoPtr->uView == LV_VIEW_DETAILS && infoPtr->dwLvExStyle & LVS_EX_FULLROWSELECT &&
2639         SendMessageW(infoPtr->hwndHeader, HDM_ORDERTOINDEX, 0, 0))
2640     {
2641         OffsetRect(lprcBox, Origin.x, Position.y + Origin.y);
2642     }
2643     else
2644         OffsetRect(lprcBox, Position.x + Origin.x, Position.y + Origin.y);
2645 }
2646 
2647 /* LISTVIEW_MapIdToIndex helper */
2648 static INT CALLBACK MapIdSearchCompare(LPVOID p1, LPVOID p2, LPARAM lParam)
2649 {
2650     ITEM_ID *id1 = (ITEM_ID*)p1;
2651     ITEM_ID *id2 = (ITEM_ID*)p2;
2652 
2653     if (id1->id == id2->id) return 0;
2654 
2655     return (id1->id < id2->id) ? -1 : 1;
2656 }
2657 
2658 /***
2659  * DESCRIPTION:
2660  * Returns the item index for id specified.
2661  *
2662  * PARAMETER(S):
2663  * [I] infoPtr : valid pointer to the listview structure
2664  * [I] iID : item id to get index for
2665  *
2666  * RETURN:
2667  * Item index, or -1 on failure.
2668  */
2669 static INT LISTVIEW_MapIdToIndex(const LISTVIEW_INFO *infoPtr, UINT iID)
2670 {
2671     ITEM_ID ID;
2672     INT index;
2673 
2674     TRACE("iID=%d\n", iID);
2675 
2676     if (infoPtr->dwStyle & LVS_OWNERDATA) return -1;
2677     if (infoPtr->nItemCount == 0) return -1;
2678 
2679     ID.id = iID;
2680     index = DPA_Search(infoPtr->hdpaItemIds, &ID, -1, MapIdSearchCompare, 0, DPAS_SORTED);
2681 
2682     if (index != -1)
2683     {
2684         ITEM_ID *lpID = DPA_GetPtr(infoPtr->hdpaItemIds, index);
2685         return DPA_GetPtrIndex(infoPtr->hdpaItems, lpID->item);
2686     }
2687 
2688     return -1;
2689 }
2690 
2691 /***
2692  * DESCRIPTION:
2693  * Returns the item id for index given.
2694  *
2695  * PARAMETER(S):
2696  * [I] infoPtr : valid pointer to the listview structure
2697  * [I] iItem : item index to get id for
2698  *
2699  * RETURN:
2700  * Item id.
2701  */
2702 static DWORD LISTVIEW_MapIndexToId(const LISTVIEW_INFO *infoPtr, INT iItem)
2703 {
2704     ITEM_INFO *lpItem;
2705     HDPA hdpaSubItems;
2706 
2707     TRACE("iItem=%d\n", iItem);
2708 
2709     if (infoPtr->dwStyle & LVS_OWNERDATA) return -1;
2710     if (iItem < 0 || iItem >= infoPtr->nItemCount) return -1;
2711 
2712     hdpaSubItems = DPA_GetPtr(infoPtr->hdpaItems, iItem);
2713     lpItem = DPA_GetPtr(hdpaSubItems, 0);
2714 
2715     return lpItem->id->id;
2716 }
2717 
2718 /***
2719  * DESCRIPTION:
2720  * Returns the current icon position, and advances it along the top.
2721  * The returned position is not offset by Origin.
2722  *
2723  * PARAMETER(S):
2724  * [I] infoPtr : valid pointer to the listview structure
2725  * [O] lpPos : will get the current icon position
2726  * [I] nItem : item id to get position for
2727  *
2728  * RETURN:
2729  * None
2730  */
2731 #ifdef __REACTOS__
2732 static void LISTVIEW_NextIconPosTop(LISTVIEW_INFO *infoPtr, LPPOINT lpPos, INT nItem)
2733 #else
2734 static void LISTVIEW_NextIconPosTop(LISTVIEW_INFO *infoPtr, LPPOINT lpPos)
2735 #endif
2736 {
2737     INT nListWidth = infoPtr->rcList.right - infoPtr->rcList.left;
2738 
2739     *lpPos = infoPtr->currIconPos;
2740 
2741     infoPtr->currIconPos.x += infoPtr->nItemWidth;
2742     if (infoPtr->currIconPos.x + infoPtr->nItemWidth <= nListWidth) return;
2743 
2744     infoPtr->currIconPos.x  = 0;
2745     infoPtr->currIconPos.y += infoPtr->nItemHeight;
2746 }
2747 
2748 
2749 /***
2750  * DESCRIPTION:
2751  * Returns the current icon position, and advances it down the left edge.
2752  * The returned position is not offset by Origin.
2753  *
2754  * PARAMETER(S):
2755  * [I] infoPtr : valid pointer to the listview structure
2756  * [O] lpPos : will get the current icon position
2757  * [I] nItem : item id to get position for
2758  *
2759  * RETURN:
2760  * None
2761  */
2762 #ifdef __REACTOS__
2763 static void LISTVIEW_NextIconPosLeft(LISTVIEW_INFO *infoPtr, LPPOINT lpPos, INT nItem)
2764 #else
2765 static void LISTVIEW_NextIconPosLeft(LISTVIEW_INFO *infoPtr, LPPOINT lpPos)
2766 #endif
2767 {
2768     INT nListHeight = infoPtr->rcList.bottom - infoPtr->rcList.top;
2769 
2770     *lpPos = infoPtr->currIconPos;
2771 
2772     infoPtr->currIconPos.y += infoPtr->nItemHeight;
2773     if (infoPtr->currIconPos.y + infoPtr->nItemHeight <= nListHeight) return;
2774 
2775     infoPtr->currIconPos.x += infoPtr->nItemWidth;
2776     infoPtr->currIconPos.y  = 0;
2777 }
2778 
2779 
2780 #ifdef __REACTOS__
2781 /***
2782  * DESCRIPTION:
2783  * Returns the grid position closest to the already placed icon.
2784  * The returned position is not offset by Origin.
2785  *
2786  * PARAMETER(S):
2787  * [I] infoPtr : valid pointer to the listview structure
2788  * [O] lpPos : will get the current icon position
2789  * [I] nItem : item id to get position for
2790  *
2791  * RETURN:
2792  * None
2793  */
2794 static void LISTVIEW_NextIconPosSnap(LISTVIEW_INFO *infoPtr, LPPOINT lpPos, INT nItem)
2795 {
2796     INT nListHeight = infoPtr->rcList.bottom - infoPtr->rcList.top;
2797     INT nListWidth = infoPtr->rcList.right - infoPtr->rcList.left;
2798     INT nMaxColumns = nListWidth / infoPtr->nItemWidth;
2799     INT nMaxRows = nListHeight / infoPtr->nItemHeight;
2800     POINT oldPosition;
2801 
2802     // get the existing x and y position and then snap to the closest grid square
2803     oldPosition.x = (LONG_PTR)DPA_GetPtr(infoPtr->hdpaPosX, nItem);
2804     oldPosition.y = (LONG_PTR)DPA_GetPtr(infoPtr->hdpaPosY, nItem);
2805 
2806     // FIXME: This could should deal with multiple icons in the same grid square
2807     // equivalent of max(0, round(oldPosition / itemSize) * itemSize), but without need for 'round' function
2808     (*lpPos).x = max(0, oldPosition.x + (infoPtr->nItemWidth >> 1) - (oldPosition.x + (infoPtr->nItemWidth >> 1)) % infoPtr->nItemWidth);
2809     (*lpPos).y = max(0, oldPosition.y + (infoPtr->nItemHeight >> 1) - (oldPosition.y + (infoPtr->nItemHeight >> 1)) % infoPtr->nItemHeight);
2810 
2811     // deal with any icons that have gone out of range
2812     if ((*lpPos).x > nListWidth) (*lpPos).x = nMaxColumns * infoPtr->nItemWidth;
2813     if ((*lpPos).y > nListHeight) (*lpPos).y = nMaxRows * infoPtr->nItemHeight;
2814 }
2815 #endif
2816 
2817 
2818 /***
2819  * DESCRIPTION:
2820  * Moves an icon to the specified position.
2821  * It takes care of invalidating the item, etc.
2822  *
2823  * PARAMETER(S):
2824  * [I] infoPtr : valid pointer to the listview structure
2825  * [I] nItem : the item to move
2826  * [I] lpPos : the new icon position
2827  * [I] isNew : flags the item as being new
2828  *
2829  * RETURN:
2830  *   Success: TRUE
2831  *   Failure: FALSE
2832  */
2833 static BOOL LISTVIEW_MoveIconTo(const LISTVIEW_INFO *infoPtr, INT nItem, const POINT *lppt, BOOL isNew)
2834 {
2835     POINT old;
2836 
2837     if (!isNew)
2838     {
2839         old.x = (LONG_PTR)DPA_GetPtr(infoPtr->hdpaPosX, nItem);
2840         old.y = (LONG_PTR)DPA_GetPtr(infoPtr->hdpaPosY, nItem);
2841 
2842         if (lppt->x == old.x && lppt->y == old.y) return TRUE;
2843 	LISTVIEW_InvalidateItem(infoPtr, nItem);
2844     }
2845 
2846     /* Allocating a POINTER for every item is too resource intensive,
2847      * so we'll keep the (x,y) in different arrays */
2848     if (!DPA_SetPtr(infoPtr->hdpaPosX, nItem, (void *)(LONG_PTR)lppt->x)) return FALSE;
2849     if (!DPA_SetPtr(infoPtr->hdpaPosY, nItem, (void *)(LONG_PTR)lppt->y)) return FALSE;
2850 
2851     LISTVIEW_InvalidateItem(infoPtr, nItem);
2852 
2853     return TRUE;
2854 }
2855 
2856 /***
2857  * DESCRIPTION:
2858  * Arranges listview items in icon display mode.
2859  *
2860  * PARAMETER(S):
2861  * [I] infoPtr : valid pointer to the listview structure
2862  * [I] nAlignCode : alignment code
2863  *
2864  * RETURN:
2865  *   SUCCESS : TRUE
2866  *   FAILURE : FALSE
2867  */
2868 static BOOL LISTVIEW_Arrange(LISTVIEW_INFO *infoPtr, INT nAlignCode)
2869 {
2870 #ifdef __REACTOS__
2871     void (*next_pos)(LISTVIEW_INFO *, LPPOINT, INT);
2872 #else
2873     void (*next_pos)(LISTVIEW_INFO *, LPPOINT);
2874 #endif
2875     POINT pos;
2876     INT i;
2877 
2878     if (infoPtr->uView != LV_VIEW_ICON && infoPtr->uView != LV_VIEW_SMALLICON) return FALSE;
2879 
2880     TRACE("nAlignCode=%d\n", nAlignCode);
2881 
2882     if (nAlignCode == LVA_DEFAULT)
2883     {
2884 	if (infoPtr->dwStyle & LVS_ALIGNLEFT) nAlignCode = LVA_ALIGNLEFT;
2885         else nAlignCode = LVA_ALIGNTOP;
2886     }
2887 
2888     switch (nAlignCode)
2889     {
2890     case LVA_ALIGNLEFT:  next_pos = LISTVIEW_NextIconPosLeft; break;
2891     case LVA_ALIGNTOP:   next_pos = LISTVIEW_NextIconPosTop;  break;
2892 #ifdef __REACTOS__
2893     case LVA_SNAPTOGRID: next_pos = LISTVIEW_NextIconPosSnap; break;
2894 #else
2895     case LVA_SNAPTOGRID: next_pos = LISTVIEW_NextIconPosTop;  break; /* FIXME */
2896 #endif
2897     default: return FALSE;
2898     }
2899 
2900     infoPtr->currIconPos.x = infoPtr->currIconPos.y = 0;
2901     for (i = 0; i < infoPtr->nItemCount; i++)
2902     {
2903 #ifdef __REACTOS__
2904     next_pos(infoPtr, &pos, i);
2905 #else
2906     next_pos(infoPtr, &pos);
2907 #endif
2908 	LISTVIEW_MoveIconTo(infoPtr, i, &pos, FALSE);
2909     }
2910 
2911     return TRUE;
2912 }
2913 
2914 /***
2915  * DESCRIPTION:
2916  * Retrieves the bounding rectangle of all the items, not offset by Origin.
2917  * For LVS_REPORT always returns empty rectangle.
2918  *
2919  * PARAMETER(S):
2920  * [I] infoPtr : valid pointer to the listview structure
2921  * [O] lprcView : bounding rectangle
2922  *
2923  * RETURN:
2924  *   SUCCESS : TRUE
2925  *   FAILURE : FALSE
2926  */
2927 static void LISTVIEW_GetAreaRect(const LISTVIEW_INFO *infoPtr, LPRECT lprcView)
2928 {
2929     INT i, x, y;
2930 
2931     SetRectEmpty(lprcView);
2932 
2933     switch (infoPtr->uView)
2934     {
2935     case LV_VIEW_ICON:
2936     case LV_VIEW_SMALLICON:
2937 	for (i = 0; i < infoPtr->nItemCount; i++)
2938 	{
2939 	    x = (LONG_PTR)DPA_GetPtr(infoPtr->hdpaPosX, i);
2940             y = (LONG_PTR)DPA_GetPtr(infoPtr->hdpaPosY, i);
2941 	    lprcView->right = max(lprcView->right, x);
2942 	    lprcView->bottom = max(lprcView->bottom, y);
2943 	}
2944 	if (infoPtr->nItemCount > 0)
2945 	{
2946 	    lprcView->right += infoPtr->nItemWidth;
2947 	    lprcView->bottom += infoPtr->nItemHeight;
2948 	}
2949 	break;
2950 
2951     case LV_VIEW_LIST:
2952 	y = LISTVIEW_GetCountPerColumn(infoPtr);
2953 	x = infoPtr->nItemCount / y;
2954 	if (infoPtr->nItemCount % y) x++;
2955 	lprcView->right = x * infoPtr->nItemWidth;
2956 	lprcView->bottom = y * infoPtr->nItemHeight;
2957 	break;
2958     }
2959 }
2960 
2961 /***
2962  * DESCRIPTION:
2963  * Retrieves the bounding rectangle of all the items.
2964  *
2965  * PARAMETER(S):
2966  * [I] infoPtr : valid pointer to the listview structure
2967  * [O] lprcView : bounding rectangle
2968  *
2969  * RETURN:
2970  *   SUCCESS : TRUE
2971  *   FAILURE : FALSE
2972  */
2973 static BOOL LISTVIEW_GetViewRect(const LISTVIEW_INFO *infoPtr, LPRECT lprcView)
2974 {
2975     POINT ptOrigin;
2976 
2977     TRACE("(lprcView=%p)\n", lprcView);
2978 
2979     if (!lprcView) return FALSE;
2980 
2981     LISTVIEW_GetAreaRect(infoPtr, lprcView);
2982 
2983     if (infoPtr->uView != LV_VIEW_DETAILS)
2984     {
2985         LISTVIEW_GetOrigin(infoPtr, &ptOrigin);
2986         OffsetRect(lprcView, ptOrigin.x, ptOrigin.y);
2987     }
2988 
2989     TRACE("lprcView=%s\n", wine_dbgstr_rect(lprcView));
2990 
2991     return TRUE;
2992 }
2993 
2994 /***
2995  * DESCRIPTION:
2996  * Retrieves the subitem pointer associated with the subitem index.
2997  *
2998  * PARAMETER(S):
2999  * [I] hdpaSubItems : DPA handle for a specific item
3000  * [I] nSubItem : index of subitem
3001  *
3002  * RETURN:
3003  *   SUCCESS : subitem pointer
3004  *   FAILURE : NULL
3005  */
3006 static SUBITEM_INFO* LISTVIEW_GetSubItemPtr(HDPA hdpaSubItems, INT nSubItem)
3007 {
3008     SUBITEM_INFO *lpSubItem;
3009     INT i;
3010 
3011     /* we should binary search here if need be */
3012     for (i = 1; i < DPA_GetPtrCount(hdpaSubItems); i++)
3013     {
3014         lpSubItem = DPA_GetPtr(hdpaSubItems, i);
3015 	if (lpSubItem->iSubItem == nSubItem)
3016 	    return lpSubItem;
3017     }
3018 
3019     return NULL;
3020 }
3021 
3022 
3023 /***
3024  * DESCRIPTION:
3025  * Calculates the desired item width.
3026  *
3027  * PARAMETER(S):
3028  * [I] infoPtr : valid pointer to the listview structure
3029  *
3030  * RETURN:
3031  *  The desired item width.
3032  */
3033 static INT LISTVIEW_CalculateItemWidth(const LISTVIEW_INFO *infoPtr)
3034 {
3035     INT nItemWidth = 0;
3036 
3037     TRACE("uView=%d\n", infoPtr->uView);
3038 
3039     if (infoPtr->uView == LV_VIEW_ICON)
3040 	nItemWidth = infoPtr->iconSpacing.cx;
3041     else if (infoPtr->uView == LV_VIEW_DETAILS)
3042     {
3043 	if (DPA_GetPtrCount(infoPtr->hdpaColumns) > 0)
3044 	{
3045 	    RECT rcHeader;
3046 	    INT index;
3047 
3048 	    index = SendMessageW(infoPtr->hwndHeader, HDM_ORDERTOINDEX,
3049                                  DPA_GetPtrCount(infoPtr->hdpaColumns) - 1, 0);
3050 
3051 	    LISTVIEW_GetHeaderRect(infoPtr, index, &rcHeader);
3052             nItemWidth = rcHeader.right;
3053 	}
3054     }
3055     else /* LV_VIEW_SMALLICON, or LV_VIEW_LIST */
3056     {
3057 	WCHAR szDispText[DISP_TEXT_SIZE] = { '\0' };
3058 	LVITEMW lvItem;
3059 	INT i;
3060 
3061 	lvItem.mask = LVIF_TEXT;
3062 	lvItem.iSubItem = 0;
3063 
3064 	for (i = 0; i < infoPtr->nItemCount; i++)
3065 	{
3066 	    lvItem.iItem = i;
3067 	    lvItem.pszText = szDispText;
3068 	    lvItem.cchTextMax = DISP_TEXT_SIZE;
3069 	    if (LISTVIEW_GetItemW(infoPtr, &lvItem))
3070 		nItemWidth = max(LISTVIEW_GetStringWidthT(infoPtr, lvItem.pszText, TRUE),
3071 				 nItemWidth);
3072 	}
3073 
3074         if (infoPtr->himlSmall) nItemWidth += infoPtr->iconSize.cx;
3075         if (infoPtr->himlState) nItemWidth += infoPtr->iconStateSize.cx;
3076 
3077         nItemWidth = max(DEFAULT_COLUMN_WIDTH, nItemWidth + WIDTH_PADDING);
3078     }
3079 
3080     return nItemWidth;
3081 }
3082 
3083 /***
3084  * DESCRIPTION:
3085  * Calculates the desired item height.
3086  *
3087  * PARAMETER(S):
3088  * [I] infoPtr : valid pointer to the listview structure
3089  *
3090  * RETURN:
3091  *  The desired item height.
3092  */
3093 static INT LISTVIEW_CalculateItemHeight(const LISTVIEW_INFO *infoPtr)
3094 {
3095     INT nItemHeight;
3096 
3097     TRACE("uView=%d\n", infoPtr->uView);
3098 
3099     if (infoPtr->uView == LV_VIEW_ICON)
3100 	nItemHeight = infoPtr->iconSpacing.cy;
3101     else
3102     {
3103 	nItemHeight = infoPtr->ntmHeight;
3104 	if (infoPtr->himlState)
3105 	    nItemHeight = max(nItemHeight, infoPtr->iconStateSize.cy);
3106 	if (infoPtr->himlSmall)
3107 	    nItemHeight = max(nItemHeight, infoPtr->iconSize.cy);
3108 	nItemHeight += HEIGHT_PADDING;
3109     if (infoPtr->nMeasureItemHeight > 0)
3110         nItemHeight = infoPtr->nMeasureItemHeight;
3111     }
3112 
3113     return max(nItemHeight, 1);
3114 }
3115 
3116 /***
3117  * DESCRIPTION:
3118  * Updates the width, and height of an item.
3119  *
3120  * PARAMETER(S):
3121  * [I] infoPtr : valid pointer to the listview structure
3122  *
3123  * RETURN:
3124  *  None.
3125  */
3126 static inline void LISTVIEW_UpdateItemSize(LISTVIEW_INFO *infoPtr)
3127 {
3128     infoPtr->nItemWidth = LISTVIEW_CalculateItemWidth(infoPtr);
3129     infoPtr->nItemHeight = LISTVIEW_CalculateItemHeight(infoPtr);
3130 }
3131 
3132 
3133 /***
3134  * DESCRIPTION:
3135  * Retrieves and saves important text metrics info for the current
3136  * Listview font.
3137  *
3138  * PARAMETER(S):
3139  * [I] infoPtr : valid pointer to the listview structure
3140  *
3141  */
3142 static void LISTVIEW_SaveTextMetrics(LISTVIEW_INFO *infoPtr)
3143 {
3144     HDC hdc = GetDC(infoPtr->hwndSelf);
3145     HFONT hFont = infoPtr->hFont ? infoPtr->hFont : infoPtr->hDefaultFont;
3146     HFONT hOldFont = SelectObject(hdc, hFont);
3147     TEXTMETRICW tm;
3148     SIZE sz;
3149 
3150     if (GetTextMetricsW(hdc, &tm))
3151     {
3152 	infoPtr->ntmHeight = tm.tmHeight;
3153 	infoPtr->ntmMaxCharWidth = tm.tmMaxCharWidth;
3154     }
3155 
3156     if (GetTextExtentPoint32A(hdc, "...", 3, &sz))
3157 	infoPtr->nEllipsisWidth = sz.cx;
3158 
3159     SelectObject(hdc, hOldFont);
3160     ReleaseDC(infoPtr->hwndSelf, hdc);
3161 
3162     TRACE("tmHeight=%d\n", infoPtr->ntmHeight);
3163 }
3164 
3165 /***
3166  * DESCRIPTION:
3167  * A compare function for ranges
3168  *
3169  * PARAMETER(S)
3170  * [I] range1 : pointer to range 1;
3171  * [I] range2 : pointer to range 2;
3172  * [I] flags : flags
3173  *
3174  * RETURNS:
3175  * > 0 : if range 1 > range 2
3176  * < 0 : if range 2 > range 1
3177  * = 0 : if range intersects range 2
3178  */
3179 static INT CALLBACK ranges_cmp(LPVOID range1, LPVOID range2, LPARAM flags)
3180 {
3181     INT cmp;
3182 
3183     if (((RANGE*)range1)->upper <= ((RANGE*)range2)->lower)
3184 	cmp = -1;
3185     else if (((RANGE*)range2)->upper <= ((RANGE*)range1)->lower)
3186 	cmp = 1;
3187     else
3188 	cmp = 0;
3189 
3190     TRACE("range1=%s, range2=%s, cmp=%d\n", debugrange(range1), debugrange(range2), cmp);
3191 
3192     return cmp;
3193 }
3194 
3195 #define ranges_check(ranges, desc) if (TRACE_ON(listview)) ranges_assert(ranges, desc, __FILE__, __LINE__)
3196 
3197 static void ranges_assert(RANGES ranges, LPCSTR desc, const char *file, int line)
3198 {
3199     INT i;
3200     RANGE *prev, *curr;
3201 
3202     TRACE("*** Checking %s:%d:%s ***\n", file, line, desc);
3203     assert (ranges);
3204     assert (DPA_GetPtrCount(ranges->hdpa) >= 0);
3205     ranges_dump(ranges);
3206     if (DPA_GetPtrCount(ranges->hdpa) > 0)
3207     {
3208 	prev = DPA_GetPtr(ranges->hdpa, 0);
3209 	assert (prev->lower >= 0 && prev->lower < prev->upper);
3210 	for (i = 1; i < DPA_GetPtrCount(ranges->hdpa); i++)
3211 	{
3212 	    curr = DPA_GetPtr(ranges->hdpa, i);
3213 	    assert (prev->upper <= curr->lower);
3214 	    assert (curr->lower < curr->upper);
3215 	    prev = curr;
3216 	}
3217     }
3218     TRACE("--- Done checking---\n");
3219 }
3220 
3221 static RANGES ranges_create(int count)
3222 {
3223     RANGES ranges = Alloc(sizeof(struct tagRANGES));
3224     if (!ranges) return NULL;
3225     ranges->hdpa = DPA_Create(count);
3226     if (ranges->hdpa) return ranges;
3227     Free(ranges);
3228     return NULL;
3229 }
3230 
3231 static void ranges_clear(RANGES ranges)
3232 {
3233     INT i;
3234 
3235     for(i = 0; i < DPA_GetPtrCount(ranges->hdpa); i++)
3236 	Free(DPA_GetPtr(ranges->hdpa, i));
3237     DPA_DeleteAllPtrs(ranges->hdpa);
3238 }
3239 
3240 
3241 static void ranges_destroy(RANGES ranges)
3242 {
3243     if (!ranges) return;
3244     ranges_clear(ranges);
3245     DPA_Destroy(ranges->hdpa);
3246     Free(ranges);
3247 }
3248 
3249 static RANGES ranges_clone(RANGES ranges)
3250 {
3251     RANGES clone;
3252     INT i;
3253 
3254     if (!(clone = ranges_create(DPA_GetPtrCount(ranges->hdpa)))) goto fail;
3255 
3256     for (i = 0; i < DPA_GetPtrCount(ranges->hdpa); i++)
3257     {
3258         RANGE *newrng = Alloc(sizeof(RANGE));
3259 	if (!newrng) goto fail;
3260 	*newrng = *((RANGE*)DPA_GetPtr(ranges->hdpa, i));
3261         if (!DPA_SetPtr(clone->hdpa, i, newrng))
3262         {
3263             Free(newrng);
3264             goto fail;
3265         }
3266     }
3267     return clone;
3268 
3269 fail:
3270     TRACE ("clone failed\n");
3271     ranges_destroy(clone);
3272     return NULL;
3273 }
3274 
3275 static RANGES ranges_diff(RANGES ranges, RANGES sub)
3276 {
3277     INT i;
3278 
3279     for (i = 0; i < DPA_GetPtrCount(sub->hdpa); i++)
3280 	ranges_del(ranges, *((RANGE *)DPA_GetPtr(sub->hdpa, i)));
3281 
3282     return ranges;
3283 }
3284 
3285 static void ranges_dump(RANGES ranges)
3286 {
3287     INT i;
3288 
3289     for (i = 0; i < DPA_GetPtrCount(ranges->hdpa); i++)
3290     	TRACE("   %s\n", debugrange(DPA_GetPtr(ranges->hdpa, i)));
3291 }
3292 
3293 static inline BOOL ranges_contain(RANGES ranges, INT nItem)
3294 {
3295     RANGE srchrng = { nItem, nItem + 1 };
3296 
3297     TRACE("(nItem=%d)\n", nItem);
3298     ranges_check(ranges, "before contain");
3299     return DPA_Search(ranges->hdpa, &srchrng, 0, ranges_cmp, 0, DPAS_SORTED) != -1;
3300 }
3301 
3302 static INT ranges_itemcount(RANGES ranges)
3303 {
3304     INT i, count = 0;
3305 
3306     for (i = 0; i < DPA_GetPtrCount(ranges->hdpa); i++)
3307     {
3308 	RANGE *sel = DPA_GetPtr(ranges->hdpa, i);
3309 	count += sel->upper - sel->lower;
3310     }
3311 
3312     return count;
3313 }
3314 
3315 static BOOL ranges_shift(RANGES ranges, INT nItem, INT delta, INT nUpper)
3316 {
3317     RANGE srchrng = { nItem, nItem + 1 }, *chkrng;
3318     INT index;
3319 
3320     index = DPA_Search(ranges->hdpa, &srchrng, 0, ranges_cmp, 0, DPAS_SORTED | DPAS_INSERTAFTER);
3321     if (index == -1) return TRUE;
3322 
3323     for (; index < DPA_GetPtrCount(ranges->hdpa); index++)
3324     {
3325 	chkrng = DPA_GetPtr(ranges->hdpa, index);
3326     	if (chkrng->lower >= nItem)
3327 	    chkrng->lower = max(min(chkrng->lower + delta, nUpper - 1), 0);
3328         if (chkrng->upper > nItem)
3329 	    chkrng->upper = max(min(chkrng->upper + delta, nUpper), 0);
3330     }
3331     return TRUE;
3332 }
3333 
3334 static BOOL ranges_add(RANGES ranges, RANGE range)
3335 {
3336     RANGE srchrgn;
3337     INT index;
3338 
3339     TRACE("(%s)\n", debugrange(&range));
3340     ranges_check(ranges, "before add");
3341 
3342     /* try find overlapping regions first */
3343     srchrgn.lower = range.lower - 1;
3344     srchrgn.upper = range.upper + 1;
3345     index = DPA_Search(ranges->hdpa, &srchrgn, 0, ranges_cmp, 0, DPAS_SORTED);
3346 
3347     if (index == -1)
3348     {
3349 	RANGE *newrgn;
3350 
3351 	TRACE("Adding new range\n");
3352 
3353 	/* create the brand new range to insert */
3354         newrgn = Alloc(sizeof(RANGE));
3355 	if(!newrgn) goto fail;
3356 	*newrgn = range;
3357 
3358 	/* figure out where to insert it */
3359 	index = DPA_Search(ranges->hdpa, newrgn, 0, ranges_cmp, 0, DPAS_SORTED | DPAS_INSERTAFTER);
3360 	TRACE("index=%d\n", index);
3361 	if (index == -1) index = 0;
3362 
3363 	/* and get it over with */
3364 	if (DPA_InsertPtr(ranges->hdpa, index, newrgn) == -1)
3365 	{
3366 	    Free(newrgn);
3367 	    goto fail;
3368 	}
3369     }
3370     else
3371     {
3372 	RANGE *chkrgn, *mrgrgn;
3373 	INT fromindex, mergeindex;
3374 
3375 	chkrgn = DPA_GetPtr(ranges->hdpa, index);
3376 	TRACE("Merge with %s @%d\n", debugrange(chkrgn), index);
3377 
3378 	chkrgn->lower = min(range.lower, chkrgn->lower);
3379 	chkrgn->upper = max(range.upper, chkrgn->upper);
3380 
3381 	TRACE("New range %s @%d\n", debugrange(chkrgn), index);
3382 
3383         /* merge now common ranges */
3384 	fromindex = 0;
3385 	srchrgn.lower = chkrgn->lower - 1;
3386 	srchrgn.upper = chkrgn->upper + 1;
3387 
3388 	do
3389 	{
3390 	    mergeindex = DPA_Search(ranges->hdpa, &srchrgn, fromindex, ranges_cmp, 0, 0);
3391 	    if (mergeindex == -1) break;
3392 	    if (mergeindex == index)
3393 	    {
3394 		fromindex = index + 1;
3395 		continue;
3396 	    }
3397 
3398 	    TRACE("Merge with index %i\n", mergeindex);
3399 
3400 	    mrgrgn = DPA_GetPtr(ranges->hdpa, mergeindex);
3401 	    chkrgn->lower = min(chkrgn->lower, mrgrgn->lower);
3402 	    chkrgn->upper = max(chkrgn->upper, mrgrgn->upper);
3403 	    Free(mrgrgn);
3404 	    DPA_DeletePtr(ranges->hdpa, mergeindex);
3405 	    if (mergeindex < index) index --;
3406 	} while(1);
3407     }
3408 
3409     ranges_check(ranges, "after add");
3410     return TRUE;
3411 
3412 fail:
3413     ranges_check(ranges, "failed add");
3414     return FALSE;
3415 }
3416 
3417 static BOOL ranges_del(RANGES ranges, RANGE range)
3418 {
3419     RANGE *chkrgn;
3420     INT index;
3421 
3422     TRACE("(%s)\n", debugrange(&range));
3423     ranges_check(ranges, "before del");
3424 
3425     /* we don't use DPAS_SORTED here, since we need *
3426      * to find the first overlapping range          */
3427     index = DPA_Search(ranges->hdpa, &range, 0, ranges_cmp, 0, 0);
3428     while(index != -1)
3429     {
3430 	chkrgn = DPA_GetPtr(ranges->hdpa, index);
3431 
3432 	TRACE("Matches range %s @%d\n", debugrange(chkrgn), index);
3433 
3434 	/* case 1: Same range */
3435 	if ( (chkrgn->upper == range.upper) &&
3436 	     (chkrgn->lower == range.lower) )
3437 	{
3438 	    DPA_DeletePtr(ranges->hdpa, index);
3439 	    Free(chkrgn);
3440 	    break;
3441 	}
3442 	/* case 2: engulf */
3443 	else if ( (chkrgn->upper <= range.upper) &&
3444 		  (chkrgn->lower >= range.lower) )
3445 	{
3446 	    DPA_DeletePtr(ranges->hdpa, index);
3447 	    Free(chkrgn);
3448 	}
3449 	/* case 3: overlap upper */
3450 	else if ( (chkrgn->upper <= range.upper) &&
3451 		  (chkrgn->lower < range.lower) )
3452 	{
3453 	    chkrgn->upper = range.lower;
3454 	}
3455 	/* case 4: overlap lower */
3456 	else if ( (chkrgn->upper > range.upper) &&
3457 		  (chkrgn->lower >= range.lower) )
3458 	{
3459 	    chkrgn->lower = range.upper;
3460 	    break;
3461 	}
3462 	/* case 5: fully internal */
3463 	else
3464 	{
3465 	    RANGE *newrgn;
3466 
3467 	    if (!(newrgn = Alloc(sizeof(RANGE)))) goto fail;
3468 	    newrgn->lower = chkrgn->lower;
3469 	    newrgn->upper = range.lower;
3470 	    chkrgn->lower = range.upper;
3471 	    if (DPA_InsertPtr(ranges->hdpa, index, newrgn) == -1)
3472 	    {
3473 		Free(newrgn);
3474 		goto fail;
3475 	    }
3476 	    break;
3477 	}
3478 
3479 	index = DPA_Search(ranges->hdpa, &range, index, ranges_cmp, 0, 0);
3480     }
3481 
3482     ranges_check(ranges, "after del");
3483     return TRUE;
3484 
3485 fail:
3486     ranges_check(ranges, "failed del");
3487     return FALSE;
3488 }
3489 
3490 /***
3491 * DESCRIPTION:
3492 * Removes all selection ranges
3493 *
3494 * Parameters(s):
3495 * [I] infoPtr : valid pointer to the listview structure
3496 * [I] toSkip : item range to skip removing the selection
3497 *
3498 * RETURNS:
3499 *   SUCCESS : TRUE
3500 *   FAILURE : FALSE
3501 */
3502 static BOOL LISTVIEW_DeselectAllSkipItems(LISTVIEW_INFO *infoPtr, RANGES toSkip)
3503 {
3504     LVITEMW lvItem;
3505     ITERATOR i;
3506     RANGES clone;
3507 
3508     TRACE("()\n");
3509 
3510     lvItem.state = 0;
3511     lvItem.stateMask = LVIS_SELECTED;
3512 
3513     /* need to clone the DPA because callbacks can change it */
3514     if (!(clone = ranges_clone(infoPtr->selectionRanges))) return FALSE;
3515     iterator_rangesitems(&i, ranges_diff(clone, toSkip));
3516     while(iterator_next(&i))
3517 	LISTVIEW_SetItemState(infoPtr, i.nItem, &lvItem);
3518     /* note that the iterator destructor will free the cloned range */
3519     iterator_destroy(&i);
3520 
3521     return TRUE;
3522 }
3523 
3524 static inline BOOL LISTVIEW_DeselectAllSkipItem(LISTVIEW_INFO *infoPtr, INT nItem)
3525 {
3526     RANGES toSkip;
3527 
3528     if (!(toSkip = ranges_create(1))) return FALSE;
3529     if (nItem != -1) ranges_additem(toSkip, nItem);
3530     LISTVIEW_DeselectAllSkipItems(infoPtr, toSkip);
3531     ranges_destroy(toSkip);
3532     return TRUE;
3533 }
3534 
3535 static inline BOOL LISTVIEW_DeselectAll(LISTVIEW_INFO *infoPtr)
3536 {
3537     return LISTVIEW_DeselectAllSkipItem(infoPtr, -1);
3538 }
3539 
3540 /***
3541  * DESCRIPTION:
3542  * Retrieves the number of items that are marked as selected.
3543  *
3544  * PARAMETER(S):
3545  * [I] infoPtr : valid pointer to the listview structure
3546  *
3547  * RETURN:
3548  * Number of items selected.
3549  */
3550 static INT LISTVIEW_GetSelectedCount(const LISTVIEW_INFO *infoPtr)
3551 {
3552     INT nSelectedCount = 0;
3553 
3554     if (infoPtr->uCallbackMask & LVIS_SELECTED)
3555     {
3556         INT i;
3557 	for (i = 0; i < infoPtr->nItemCount; i++)
3558   	{
3559 	    if (LISTVIEW_GetItemState(infoPtr, i, LVIS_SELECTED))
3560 		nSelectedCount++;
3561 	}
3562     }
3563     else
3564 	nSelectedCount = ranges_itemcount(infoPtr->selectionRanges);
3565 
3566     TRACE("nSelectedCount=%d\n", nSelectedCount);
3567     return nSelectedCount;
3568 }
3569 
3570 /***
3571  * DESCRIPTION:
3572  * Manages the item focus.
3573  *
3574  * PARAMETER(S):
3575  * [I] infoPtr : valid pointer to the listview structure
3576  * [I] nItem : item index
3577  *
3578  * RETURN:
3579  *   TRUE : focused item changed
3580  *   FALSE : focused item has NOT changed
3581  */
3582 static inline BOOL LISTVIEW_SetItemFocus(LISTVIEW_INFO *infoPtr, INT nItem)
3583 {
3584     INT oldFocus = infoPtr->nFocusedItem;
3585     LVITEMW lvItem;
3586 
3587     if (nItem == infoPtr->nFocusedItem) return FALSE;
3588 
3589     lvItem.state =  nItem == -1 ? 0 : LVIS_FOCUSED;
3590     lvItem.stateMask = LVIS_FOCUSED;
3591     LISTVIEW_SetItemState(infoPtr, nItem == -1 ? infoPtr->nFocusedItem : nItem, &lvItem);
3592 
3593     return oldFocus != infoPtr->nFocusedItem;
3594 }
3595 
3596 static INT shift_item(const LISTVIEW_INFO *infoPtr, INT nShiftItem, INT nItem, INT direction)
3597 {
3598     if (nShiftItem < nItem) return nShiftItem;
3599 
3600     if (nShiftItem > nItem) return nShiftItem + direction;
3601 
3602     if (direction > 0) return nShiftItem + direction;
3603 
3604     return min(nShiftItem, infoPtr->nItemCount - 1);
3605 }
3606 
3607 /* This function updates focus index.
3608 
3609 Parameters:
3610    focus : current focus index
3611    item : index of item to be added/removed
3612    direction : add/remove flag
3613 */
3614 static void LISTVIEW_ShiftFocus(LISTVIEW_INFO *infoPtr, INT focus, INT item, INT direction)
3615 {
3616     DWORD old_mask = infoPtr->notify_mask & NOTIFY_MASK_ITEM_CHANGE;
3617 
3618     infoPtr->notify_mask &= ~NOTIFY_MASK_ITEM_CHANGE;
3619     focus = shift_item(infoPtr, focus, item, direction);
3620     if (focus != infoPtr->nFocusedItem)
3621         LISTVIEW_SetItemFocus(infoPtr, focus);
3622     infoPtr->notify_mask |= old_mask;
3623 }
3624 
3625 /**
3626 * DESCRIPTION:
3627 * Updates the various indices after an item has been inserted or deleted.
3628 *
3629 * PARAMETER(S):
3630 * [I] infoPtr : valid pointer to the listview structure
3631 * [I] nItem : item index
3632 * [I] direction : Direction of shift, +1 or -1.
3633 *
3634 * RETURN:
3635 * None
3636 */
3637 static void LISTVIEW_ShiftIndices(LISTVIEW_INFO *infoPtr, INT nItem, INT direction)
3638 {
3639     TRACE("Shifting %i, %i steps\n", nItem, direction);
3640 
3641     ranges_shift(infoPtr->selectionRanges, nItem, direction, infoPtr->nItemCount);
3642     assert(abs(direction) == 1);
3643     infoPtr->nSelectionMark = shift_item(infoPtr, infoPtr->nSelectionMark, nItem, direction);
3644 
3645     /* But we are not supposed to modify nHotItem! */
3646 }
3647 
3648 /**
3649  * DESCRIPTION:
3650  * Adds a block of selections.
3651  *
3652  * PARAMETER(S):
3653  * [I] infoPtr : valid pointer to the listview structure
3654  * [I] nItem : item index
3655  *
3656  * RETURN:
3657  * Whether the window is still valid.
3658  */
3659 static BOOL LISTVIEW_AddGroupSelection(LISTVIEW_INFO *infoPtr, INT nItem)
3660 {
3661     INT nFirst = min(infoPtr->nSelectionMark, nItem);
3662     INT nLast = max(infoPtr->nSelectionMark, nItem);
3663     HWND hwndSelf = infoPtr->hwndSelf;
3664     NMLVODSTATECHANGE nmlv;
3665     DWORD old_mask;
3666     LVITEMW item;
3667     INT i;
3668 
3669     /* Temporarily disable change notification
3670      * If the control is LVS_OWNERDATA, we need to send
3671      * only one LVN_ODSTATECHANGED notification.
3672      * See MSDN documentation for LVN_ITEMCHANGED.
3673      */
3674     old_mask = infoPtr->notify_mask & NOTIFY_MASK_ITEM_CHANGE;
3675     if (infoPtr->dwStyle & LVS_OWNERDATA)
3676         infoPtr->notify_mask &= ~NOTIFY_MASK_ITEM_CHANGE;
3677 
3678     if (nFirst == -1) nFirst = nItem;
3679 
3680     item.state = LVIS_SELECTED;
3681     item.stateMask = LVIS_SELECTED;
3682 
3683     for (i = nFirst; i <= nLast; i++)
3684 	LISTVIEW_SetItemState(infoPtr,i,&item);
3685 
3686     ZeroMemory(&nmlv, sizeof(nmlv));
3687     nmlv.iFrom = nFirst;
3688     nmlv.iTo = nLast;
3689     nmlv.uOldState = 0;
3690     nmlv.uNewState = item.state;
3691 
3692     notify_hdr(infoPtr, LVN_ODSTATECHANGED, (LPNMHDR)&nmlv);
3693     if (!IsWindow(hwndSelf))
3694         return FALSE;
3695     infoPtr->notify_mask |= old_mask;
3696     return TRUE;
3697 }
3698 
3699 
3700 /***
3701  * DESCRIPTION:
3702  * Sets a single group selection.
3703  *
3704  * PARAMETER(S):
3705  * [I] infoPtr : valid pointer to the listview structure
3706  * [I] nItem : item index
3707  *
3708  * RETURN:
3709  * None
3710  */
3711 static void LISTVIEW_SetGroupSelection(LISTVIEW_INFO *infoPtr, INT nItem)
3712 {
3713     RANGES selection;
3714     DWORD old_mask;
3715     LVITEMW item;
3716     ITERATOR i;
3717 
3718     if (!(selection = ranges_create(100))) return;
3719 
3720     item.state = LVIS_SELECTED;
3721     item.stateMask = LVIS_SELECTED;
3722 
3723     if ((infoPtr->uView == LV_VIEW_LIST) || (infoPtr->uView == LV_VIEW_DETAILS))
3724     {
3725 	if (infoPtr->nSelectionMark == -1)
3726 	{
3727 	    infoPtr->nSelectionMark = nItem;
3728 	    ranges_additem(selection, nItem);
3729 	}
3730 	else
3731 	{
3732 	    RANGE sel;
3733 
3734 	    sel.lower = min(infoPtr->nSelectionMark, nItem);
3735 	    sel.upper = max(infoPtr->nSelectionMark, nItem) + 1;
3736 	    ranges_add(selection, sel);
3737 	}
3738     }
3739     else
3740     {
3741 	RECT rcItem, rcSel, rcSelMark;
3742 	POINT ptItem;
3743 
3744 	rcItem.left = LVIR_BOUNDS;
3745 	if (!LISTVIEW_GetItemRect(infoPtr, nItem, &rcItem)) {
3746 	     ranges_destroy (selection);
3747 	     return;
3748 	}
3749 	rcSelMark.left = LVIR_BOUNDS;
3750 	if (!LISTVIEW_GetItemRect(infoPtr, infoPtr->nSelectionMark, &rcSelMark)) {
3751 	     ranges_destroy (selection);
3752 	     return;
3753 	}
3754 	UnionRect(&rcSel, &rcItem, &rcSelMark);
3755 	iterator_frameditems(&i, infoPtr, &rcSel);
3756 	while(iterator_next(&i))
3757 	{
3758 	    LISTVIEW_GetItemPosition(infoPtr, i.nItem, &ptItem);
3759 	    if (PtInRect(&rcSel, ptItem)) ranges_additem(selection, i.nItem);
3760 	}
3761 	iterator_destroy(&i);
3762     }
3763 
3764     /* disable per item notifications on LVS_OWNERDATA style
3765        FIXME: single LVN_ODSTATECHANGED should be used */
3766     old_mask = infoPtr->notify_mask & NOTIFY_MASK_ITEM_CHANGE;
3767     if (infoPtr->dwStyle & LVS_OWNERDATA)
3768         infoPtr->notify_mask &= ~NOTIFY_MASK_ITEM_CHANGE;
3769 
3770     LISTVIEW_DeselectAllSkipItems(infoPtr, selection);
3771 
3772 
3773     iterator_rangesitems(&i, selection);
3774     while(iterator_next(&i))
3775 	LISTVIEW_SetItemState(infoPtr, i.nItem, &item);
3776     /* this will also destroy the selection */
3777     iterator_destroy(&i);
3778 
3779     infoPtr->notify_mask |= old_mask;
3780     LISTVIEW_SetItemFocus(infoPtr, nItem);
3781 }
3782 
3783 /***
3784  * DESCRIPTION:
3785  * Sets a single selection.
3786  *
3787  * PARAMETER(S):
3788  * [I] infoPtr : valid pointer to the listview structure
3789  * [I] nItem : item index
3790  *
3791  * RETURN:
3792  * None
3793  */
3794 static void LISTVIEW_SetSelection(LISTVIEW_INFO *infoPtr, INT nItem)
3795 {
3796     LVITEMW lvItem;
3797 
3798     TRACE("nItem=%d\n", nItem);
3799 
3800     LISTVIEW_DeselectAllSkipItem(infoPtr, nItem);
3801 
3802     lvItem.state = LVIS_FOCUSED | LVIS_SELECTED;
3803     lvItem.stateMask = LVIS_FOCUSED | LVIS_SELECTED;
3804     LISTVIEW_SetItemState(infoPtr, nItem, &lvItem);
3805 
3806     infoPtr->nSelectionMark = nItem;
3807 }
3808 
3809 /***
3810  * DESCRIPTION:
3811  * Set selection(s) with keyboard.
3812  *
3813  * PARAMETER(S):
3814  * [I] infoPtr : valid pointer to the listview structure
3815  * [I] nItem : item index
3816  * [I] space : VK_SPACE code sent
3817  *
3818  * RETURN:
3819  *   SUCCESS : TRUE (needs to be repainted)
3820  *   FAILURE : FALSE (nothing has changed)
3821  */
3822 static BOOL LISTVIEW_KeySelection(LISTVIEW_INFO *infoPtr, INT nItem, BOOL space)
3823 {
3824   /* FIXME: pass in the state */
3825   WORD wShift = GetKeyState(VK_SHIFT) & 0x8000;
3826   WORD wCtrl = GetKeyState(VK_CONTROL) & 0x8000;
3827   BOOL bResult = FALSE;
3828 
3829   TRACE("nItem=%d, wShift=%d, wCtrl=%d\n", nItem, wShift, wCtrl);
3830   if ((nItem >= 0) && (nItem < infoPtr->nItemCount))
3831   {
3832     bResult = TRUE;
3833 
3834     if (infoPtr->dwStyle & LVS_SINGLESEL || (wShift == 0 && wCtrl == 0))
3835       LISTVIEW_SetSelection(infoPtr, nItem);
3836     else
3837     {
3838       if (wShift)
3839         LISTVIEW_SetGroupSelection(infoPtr, nItem);
3840       else if (wCtrl)
3841       {
3842         LVITEMW lvItem;
3843         lvItem.state = ~LISTVIEW_GetItemState(infoPtr, nItem, LVIS_SELECTED);
3844         lvItem.stateMask = LVIS_SELECTED;
3845         if (space)
3846         {
3847             LISTVIEW_SetItemState(infoPtr, nItem, &lvItem);
3848             if (lvItem.state & LVIS_SELECTED)
3849                 infoPtr->nSelectionMark = nItem;
3850         }
3851         bResult = LISTVIEW_SetItemFocus(infoPtr, nItem);
3852       }
3853     }
3854     LISTVIEW_EnsureVisible(infoPtr, nItem, FALSE);
3855   }
3856 
3857   UpdateWindow(infoPtr->hwndSelf); /* update client area */
3858   return bResult;
3859 }
3860 
3861 static BOOL LISTVIEW_GetItemAtPt(const LISTVIEW_INFO *infoPtr, LPLVITEMW lpLVItem, POINT pt)
3862 {
3863     LVHITTESTINFO lvHitTestInfo;
3864 
3865     ZeroMemory(&lvHitTestInfo, sizeof(lvHitTestInfo));
3866     lvHitTestInfo.pt.x = pt.x;
3867     lvHitTestInfo.pt.y = pt.y;
3868 
3869     LISTVIEW_HitTest(infoPtr, &lvHitTestInfo, TRUE, FALSE);
3870 
3871     lpLVItem->mask = LVIF_PARAM;
3872     lpLVItem->iItem = lvHitTestInfo.iItem;
3873     lpLVItem->iSubItem = 0;
3874 
3875     return LISTVIEW_GetItemT(infoPtr, lpLVItem, TRUE);
3876 }
3877 
3878 static inline BOOL LISTVIEW_IsHotTracking(const LISTVIEW_INFO *infoPtr)
3879 {
3880     return ((infoPtr->dwLvExStyle & LVS_EX_TRACKSELECT) ||
3881             (infoPtr->dwLvExStyle & LVS_EX_ONECLICKACTIVATE) ||
3882             (infoPtr->dwLvExStyle & LVS_EX_TWOCLICKACTIVATE));
3883 }
3884 
3885 /***
3886  * DESCRIPTION:
3887  * Called when the mouse is being actively tracked and has hovered for a specified
3888  * amount of time
3889  *
3890  * PARAMETER(S):
3891  * [I] infoPtr : valid pointer to the listview structure
3892  * [I] fwKeys : key indicator
3893  * [I] x,y : mouse position
3894  *
3895  * RETURN:
3896  *   0 if the message was processed, non-zero if there was an error
3897  *
3898  * INFO:
3899  * LVS_EX_TRACKSELECT: An item is automatically selected when the cursor remains
3900  * over the item for a certain period of time.
3901  *
3902  */
3903 static LRESULT LISTVIEW_MouseHover(LISTVIEW_INFO *infoPtr, INT x, INT y)
3904 {
3905     NMHDR hdr;
3906 
3907     if (notify_hdr(infoPtr, NM_HOVER, &hdr)) return 0;
3908 
3909     if (LISTVIEW_IsHotTracking(infoPtr))
3910     {
3911         LVITEMW item;
3912         POINT pt;
3913 
3914         pt.x = x;
3915         pt.y = y;
3916 
3917         if (LISTVIEW_GetItemAtPt(infoPtr, &item, pt))
3918             LISTVIEW_SetSelection(infoPtr, item.iItem);
3919 
3920         SetFocus(infoPtr->hwndSelf);
3921     }
3922 
3923     return 0;
3924 }
3925 
3926 #define SCROLL_LEFT   0x1
3927 #define SCROLL_RIGHT  0x2
3928 #define SCROLL_UP     0x4
3929 #define SCROLL_DOWN   0x8
3930 
3931 /***
3932  * DESCRIPTION:
3933  * Utility routine to draw and highlight items within a marquee selection rectangle.
3934  *
3935  * PARAMETER(S):
3936  * [I] infoPtr     : valid pointer to the listview structure
3937  * [I] coords_orig : original co-ordinates of the cursor
3938  * [I] coords_offs : offsetted coordinates of the cursor
3939  * [I] offset      : offset amount
3940  * [I] scroll      : Bitmask of which directions we should scroll, if at all
3941  *
3942  * RETURN:
3943  *   None.
3944  */
3945 static void LISTVIEW_MarqueeHighlight(LISTVIEW_INFO *infoPtr, const POINT *coords_orig,
3946                                       INT scroll)
3947 {
3948     BOOL controlDown = FALSE;
3949     LVITEMW item;
3950     ITERATOR old_elems, new_elems;
3951     RECT rect;
3952     POINT coords_offs, offset;
3953 
3954     /* Ensure coordinates are within client bounds */
3955     coords_offs.x = max(min(coords_orig->x, infoPtr->rcList.right), 0);
3956     coords_offs.y = max(min(coords_orig->y, infoPtr->rcList.bottom), 0);
3957 
3958     /* Get offset */
3959     LISTVIEW_GetOrigin(infoPtr, &offset);
3960 
3961     /* Offset coordinates by the appropriate amount */
3962     coords_offs.x -= offset.x;
3963     coords_offs.y -= offset.y;
3964 
3965     if (coords_offs.x > infoPtr->marqueeOrigin.x)
3966     {
3967         rect.left = infoPtr->marqueeOrigin.x;
3968         rect.right = coords_offs.x;
3969     }
3970     else
3971     {
3972         rect.left = coords_offs.x;
3973         rect.right = infoPtr->marqueeOrigin.x;
3974     }
3975 
3976     if (coords_offs.y > infoPtr->marqueeOrigin.y)
3977     {
3978         rect.top = infoPtr->marqueeOrigin.y;
3979         rect.bottom = coords_offs.y;
3980     }
3981     else
3982     {
3983         rect.top = coords_offs.y;
3984         rect.bottom = infoPtr->marqueeOrigin.y;
3985     }
3986 
3987     /* Cancel out the old marquee rectangle and draw the new one */
3988     LISTVIEW_InvalidateRect(infoPtr, &infoPtr->marqueeDrawRect);
3989 
3990     /* Scroll by the appropriate distance if applicable - speed up scrolling as
3991        the cursor is further away */
3992 
3993     if ((scroll & SCROLL_LEFT) && (coords_orig->x <= 0))
3994         LISTVIEW_Scroll(infoPtr, coords_orig->x, 0);
3995 
3996     if ((scroll & SCROLL_RIGHT) && (coords_orig->x >= infoPtr->rcList.right))
3997         LISTVIEW_Scroll(infoPtr, (coords_orig->x - infoPtr->rcList.right), 0);
3998 
3999     if ((scroll & SCROLL_UP) && (coords_orig->y <= 0))
4000         LISTVIEW_Scroll(infoPtr, 0, coords_orig->y);
4001 
4002     if ((scroll & SCROLL_DOWN) && (coords_orig->y >= infoPtr->rcList.bottom))
4003         LISTVIEW_Scroll(infoPtr, 0, (coords_orig->y - infoPtr->rcList.bottom));
4004 
4005     iterator_frameditems_absolute(&old_elems, infoPtr, &infoPtr->marqueeRect);
4006 
4007     infoPtr->marqueeRect = rect;
4008     infoPtr->marqueeDrawRect = rect;
4009     OffsetRect(&infoPtr->marqueeDrawRect, offset.x, offset.y);
4010 
4011     iterator_frameditems_absolute(&new_elems, infoPtr, &infoPtr->marqueeRect);
4012     iterator_remove_common_items(&old_elems, &new_elems);
4013 
4014     /* Iterate over no longer selected items */
4015     while (iterator_next(&old_elems))
4016     {
4017         if (old_elems.nItem > -1)
4018         {
4019             if (LISTVIEW_GetItemState(infoPtr, old_elems.nItem, LVIS_SELECTED) == LVIS_SELECTED)
4020                 item.state = 0;
4021             else
4022                 item.state = LVIS_SELECTED;
4023 
4024             item.stateMask = LVIS_SELECTED;
4025 
4026             LISTVIEW_SetItemState(infoPtr, old_elems.nItem, &item);
4027         }
4028     }
4029     iterator_destroy(&old_elems);
4030 
4031 
4032     /* Iterate over newly selected items */
4033     if (GetKeyState(VK_CONTROL) & 0x8000)
4034         controlDown = TRUE;
4035 
4036     while (iterator_next(&new_elems))
4037     {
4038         if (new_elems.nItem > -1)
4039         {
4040             /* If CTRL is pressed, invert. If not, always select the item. */
4041             if ((controlDown) && (LISTVIEW_GetItemState(infoPtr, new_elems.nItem, LVIS_SELECTED)))
4042                 item.state = 0;
4043             else
4044                 item.state = LVIS_SELECTED;
4045 
4046             item.stateMask = LVIS_SELECTED;
4047 
4048             LISTVIEW_SetItemState(infoPtr, new_elems.nItem, &item);
4049         }
4050     }
4051     iterator_destroy(&new_elems);
4052 
4053     LISTVIEW_InvalidateRect(infoPtr, &infoPtr->marqueeDrawRect);
4054 }
4055 
4056 /***
4057  * DESCRIPTION:
4058  * Called when we are in a marquee selection that involves scrolling the listview (ie,
4059  * the cursor is outside the bounds of the client area). This is a TIMERPROC.
4060  *
4061  * PARAMETER(S):
4062  * [I] hwnd : Handle to the listview
4063  * [I] uMsg : WM_TIMER (ignored)
4064  * [I] idEvent : The timer ID interpreted as a pointer to a LISTVIEW_INFO struct
4065  * [I] dwTimer : The elapsed time (ignored)
4066  *
4067  * RETURN:
4068  *   None.
4069  */
4070 static VOID CALLBACK LISTVIEW_ScrollTimer(HWND hWnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime)
4071 {
4072     LISTVIEW_INFO *infoPtr;
4073     SCROLLINFO scrollInfo;
4074     POINT coords;
4075     INT scroll = 0;
4076 
4077     infoPtr = (LISTVIEW_INFO *) idEvent;
4078 
4079     if (!infoPtr)
4080         return;
4081 
4082     /* Get the current cursor position and convert to client coordinates */
4083     GetCursorPos(&coords);
4084     ScreenToClient(hWnd, &coords);
4085 
4086     scrollInfo.cbSize = sizeof(SCROLLINFO);
4087     scrollInfo.fMask = SIF_ALL;
4088 
4089     /* Work out in which directions we can scroll */
4090     if (GetScrollInfo(infoPtr->hwndSelf, SB_VERT, &scrollInfo))
4091     {
4092         if (scrollInfo.nPos != scrollInfo.nMin)
4093             scroll |= SCROLL_UP;
4094 
4095         if (((scrollInfo.nPage + scrollInfo.nPos) - 1) != scrollInfo.nMax)
4096             scroll |= SCROLL_DOWN;
4097     }
4098 
4099     if (GetScrollInfo(infoPtr->hwndSelf, SB_HORZ, &scrollInfo))
4100     {
4101         if (scrollInfo.nPos != scrollInfo.nMin)
4102             scroll |= SCROLL_LEFT;
4103 
4104         if (((scrollInfo.nPage + scrollInfo.nPos) - 1) != scrollInfo.nMax)
4105             scroll |= SCROLL_RIGHT;
4106     }
4107 
4108     if (((coords.x <= 0) && (scroll & SCROLL_LEFT)) ||
4109         ((coords.y <= 0) && (scroll & SCROLL_UP))   ||
4110         ((coords.x >= infoPtr->rcList.right) && (scroll & SCROLL_RIGHT)) ||
4111         ((coords.y >= infoPtr->rcList.bottom) && (scroll & SCROLL_DOWN)))
4112     {
4113         LISTVIEW_MarqueeHighlight(infoPtr, &coords, scroll);
4114     }
4115 }
4116 
4117 /***
4118  * DESCRIPTION:
4119  * Called whenever WM_MOUSEMOVE is received.
4120  *
4121  * PARAMETER(S):
4122  * [I] infoPtr : valid pointer to the listview structure
4123  * [I] fwKeys : key indicator
4124  * [I] x,y : mouse position
4125  *
4126  * RETURN:
4127  *   0 if the message is processed, non-zero if there was an error
4128  */
4129 static LRESULT LISTVIEW_MouseMove(LISTVIEW_INFO *infoPtr, WORD fwKeys, INT x, INT y)
4130 {
4131     LVHITTESTINFO ht;
4132     RECT rect;
4133     POINT pt;
4134 
4135     pt.x = x;
4136     pt.y = y;
4137 
4138     if (!(fwKeys & MK_LBUTTON))
4139         infoPtr->bLButtonDown = FALSE;
4140 
4141     if (infoPtr->bLButtonDown)
4142     {
4143         rect.left = rect.right = infoPtr->ptClickPos.x;
4144         rect.top = rect.bottom = infoPtr->ptClickPos.y;
4145 
4146         InflateRect(&rect, GetSystemMetrics(SM_CXDRAG), GetSystemMetrics(SM_CYDRAG));
4147 
4148         if (infoPtr->bMarqueeSelect)
4149         {
4150             /* Enable the timer if we're going outside our bounds, in case the user doesn't
4151                move the mouse again */
4152 
4153             if ((x <= 0) || (y <= 0) || (x >= infoPtr->rcList.right) ||
4154                 (y >= infoPtr->rcList.bottom))
4155             {
4156                 if (!infoPtr->bScrolling)
4157                 {
4158                     infoPtr->bScrolling = TRUE;
4159                     SetTimer(infoPtr->hwndSelf, (UINT_PTR) infoPtr, 1, LISTVIEW_ScrollTimer);
4160                 }
4161             }
4162             else
4163             {
4164                 infoPtr->bScrolling = FALSE;
4165                 KillTimer(infoPtr->hwndSelf, (UINT_PTR) infoPtr);
4166             }
4167 
4168             LISTVIEW_MarqueeHighlight(infoPtr, &pt, 0);
4169             return 0;
4170         }
4171 
4172         ht.pt = pt;
4173         LISTVIEW_HitTest(infoPtr, &ht, TRUE, TRUE);
4174 
4175         /* reset item marker */
4176         if (infoPtr->nLButtonDownItem != ht.iItem)
4177             infoPtr->nLButtonDownItem = -1;
4178 
4179         if (!PtInRect(&rect, pt))
4180         {
4181             /* this path covers the following:
4182                1. WM_LBUTTONDOWN over selected item (sets focus on it)
4183                2. change focus with keys
4184                3. move mouse over item from step 1 selects it and moves focus on it */
4185             if (infoPtr->nLButtonDownItem != -1 &&
4186                !LISTVIEW_GetItemState(infoPtr, infoPtr->nLButtonDownItem, LVIS_SELECTED))
4187             {
4188                 LVITEMW lvItem;
4189 
4190                 lvItem.state =  LVIS_FOCUSED | LVIS_SELECTED;
4191                 lvItem.stateMask = LVIS_FOCUSED | LVIS_SELECTED;
4192 
4193                 LISTVIEW_SetItemState(infoPtr, infoPtr->nLButtonDownItem, &lvItem);
4194                 infoPtr->nLButtonDownItem = -1;
4195             }
4196 
4197             if (!infoPtr->bDragging)
4198             {
4199                 ht.pt = infoPtr->ptClickPos;
4200                 LISTVIEW_HitTest(infoPtr, &ht, TRUE, TRUE);
4201 
4202                 /* If the click is outside the range of an item, begin a
4203                    highlight. If not, begin an item drag. */
4204                 if (ht.iItem == -1)
4205                 {
4206                     NMHDR hdr;
4207 
4208                     /* If we're allowing multiple selections, send notification.
4209                        If return value is non-zero, cancel. */
4210                     if (!(infoPtr->dwStyle & LVS_SINGLESEL) && (notify_hdr(infoPtr, LVN_MARQUEEBEGIN, &hdr) == 0))
4211                     {
4212                         /* Store the absolute coordinates of the click */
4213                         POINT offset;
4214                         LISTVIEW_GetOrigin(infoPtr, &offset);
4215 
4216                         infoPtr->marqueeOrigin.x = infoPtr->ptClickPos.x - offset.x;
4217                         infoPtr->marqueeOrigin.y = infoPtr->ptClickPos.y - offset.y;
4218 
4219                         /* Begin selection and capture mouse */
4220                         infoPtr->bMarqueeSelect = TRUE;
4221                         SetCapture(infoPtr->hwndSelf);
4222                     }
4223                 }
4224                 else
4225                 {
4226                     NMLISTVIEW nmlv;
4227 
4228                     ZeroMemory(&nmlv, sizeof(nmlv));
4229                     nmlv.iItem = ht.iItem;
4230                     nmlv.ptAction = infoPtr->ptClickPos;
4231 
4232                     notify_listview(infoPtr, LVN_BEGINDRAG, &nmlv);
4233                     infoPtr->bDragging = TRUE;
4234                 }
4235             }
4236 
4237             return 0;
4238         }
4239     }
4240 
4241     /* see if we are supposed to be tracking mouse hovering */
4242     if (LISTVIEW_IsHotTracking(infoPtr)) {
4243         TRACKMOUSEEVENT trackinfo;
4244         DWORD flags;
4245 
4246         trackinfo.cbSize = sizeof(TRACKMOUSEEVENT);
4247         trackinfo.dwFlags = TME_QUERY;
4248 
4249         /* see if we are already tracking this hwnd */
4250         _TrackMouseEvent(&trackinfo);
4251 
4252         flags = TME_LEAVE;
4253         if(infoPtr->dwLvExStyle & LVS_EX_TRACKSELECT)
4254             flags |= TME_HOVER;
4255 
4256         if((trackinfo.dwFlags & flags) != flags || trackinfo.hwndTrack != infoPtr->hwndSelf) {
4257             trackinfo.dwFlags     = flags;
4258             trackinfo.dwHoverTime = infoPtr->dwHoverTime;
4259             trackinfo.hwndTrack   = infoPtr->hwndSelf;
4260 
4261             /* call TRACKMOUSEEVENT so we receive WM_MOUSEHOVER messages */
4262             _TrackMouseEvent(&trackinfo);
4263         }
4264     }
4265 
4266     return 0;
4267 }
4268 
4269 
4270 /***
4271  * Tests whether the item is assignable to a list with style lStyle
4272  */
4273 static inline BOOL is_assignable_item(const LVITEMW *lpLVItem, LONG lStyle)
4274 {
4275     if ( (lpLVItem->mask & LVIF_TEXT) &&
4276 	(lpLVItem->pszText == LPSTR_TEXTCALLBACKW) &&
4277 	(lStyle & (LVS_SORTASCENDING | LVS_SORTDESCENDING)) ) return FALSE;
4278 
4279     return TRUE;
4280 }
4281 
4282 
4283 /***
4284  * DESCRIPTION:
4285  * Helper for LISTVIEW_SetItemT and LISTVIEW_InsertItemT: sets item attributes.
4286  *
4287  * PARAMETER(S):
4288  * [I] infoPtr : valid pointer to the listview structure
4289  * [I] lpLVItem : valid pointer to new item attributes
4290  * [I] isNew : the item being set is being inserted
4291  * [I] isW : TRUE if lpLVItem is Unicode, FALSE if it's ANSI
4292  * [O] bChanged : will be set to TRUE if the item really changed
4293  *
4294  * RETURN:
4295  *   SUCCESS : TRUE
4296  *   FAILURE : FALSE
4297  */
4298 static BOOL set_main_item(LISTVIEW_INFO *infoPtr, const LVITEMW *lpLVItem, BOOL isNew, BOOL isW, BOOL *bChanged)
4299 {
4300     ITEM_INFO *lpItem;
4301     NMLISTVIEW nmlv;
4302     UINT uChanged = 0;
4303     LVITEMW item;
4304     /* stateMask is ignored for LVM_INSERTITEM */
4305     UINT stateMask = isNew ? ~0 : lpLVItem->stateMask;
4306 
4307     TRACE("()\n");
4308 
4309     assert(lpLVItem->iItem >= 0 && lpLVItem->iItem < infoPtr->nItemCount);
4310 
4311     if (lpLVItem->mask == 0) return TRUE;
4312 
4313     if (infoPtr->dwStyle & LVS_OWNERDATA)
4314     {
4315 	/* a virtual listview only stores selection and focus */
4316 	if (lpLVItem->mask & ~LVIF_STATE)
4317 	    return FALSE;
4318 	lpItem = NULL;
4319     }
4320     else
4321     {
4322         HDPA hdpaSubItems = DPA_GetPtr(infoPtr->hdpaItems, lpLVItem->iItem);
4323         lpItem = DPA_GetPtr(hdpaSubItems, 0);
4324 	assert (lpItem);
4325     }
4326 
4327     /* we need to get the lParam and state of the item */
4328     item.iItem = lpLVItem->iItem;
4329     item.iSubItem = lpLVItem->iSubItem;
4330     item.mask = LVIF_STATE | LVIF_PARAM;
4331     item.stateMask = (infoPtr->dwStyle & LVS_OWNERDATA) ? LVIS_FOCUSED | LVIS_SELECTED : ~0;
4332 
4333     item.state = 0;
4334     item.lParam = 0;
4335     if (!isNew && !LISTVIEW_GetItemW(infoPtr, &item)) return FALSE;
4336 
4337     TRACE("oldState=%x, newState=%x\n", item.state, lpLVItem->state);
4338     /* determine what fields will change */
4339     if ((lpLVItem->mask & LVIF_STATE) && ((item.state ^ lpLVItem->state) & stateMask & ~infoPtr->uCallbackMask))
4340 	uChanged |= LVIF_STATE;
4341 
4342     if ((lpLVItem->mask & LVIF_IMAGE) && (lpItem->hdr.iImage != lpLVItem->iImage))
4343 	uChanged |= LVIF_IMAGE;
4344 
4345     if ((lpLVItem->mask & LVIF_PARAM) && (lpItem->lParam != lpLVItem->lParam))
4346 	uChanged |= LVIF_PARAM;
4347 
4348     if ((lpLVItem->mask & LVIF_INDENT) && (lpItem->iIndent != lpLVItem->iIndent))
4349 	uChanged |= LVIF_INDENT;
4350 
4351     if ((lpLVItem->mask & LVIF_TEXT) && textcmpWT(lpItem->hdr.pszText, lpLVItem->pszText, isW))
4352 	uChanged |= LVIF_TEXT;
4353 
4354     TRACE("change mask=0x%x\n", uChanged);
4355 
4356     memset(&nmlv, 0, sizeof(NMLISTVIEW));
4357     nmlv.iItem = lpLVItem->iItem;
4358     if (lpLVItem->mask & LVIF_STATE)
4359     {
4360         nmlv.uNewState = (item.state & ~stateMask) | (lpLVItem->state & stateMask);
4361         nmlv.uOldState = item.state;
4362     }
4363     nmlv.uChanged = uChanged ? uChanged : lpLVItem->mask;
4364     nmlv.lParam = item.lParam;
4365 
4366     /* Send LVN_ITEMCHANGING notification, if the item is not being inserted
4367        and we are _NOT_ virtual (LVS_OWNERDATA), and change notifications
4368        are enabled. Even nothing really changed we still need to send this,
4369        in this case uChanged mask is just set to passed item mask. */
4370     if (lpItem && !isNew && (infoPtr->notify_mask & NOTIFY_MASK_ITEM_CHANGE))
4371     {
4372       HWND hwndSelf = infoPtr->hwndSelf;
4373 
4374       if (notify_listview(infoPtr, LVN_ITEMCHANGING, &nmlv))
4375 	return FALSE;
4376       if (!IsWindow(hwndSelf))
4377 	return FALSE;
4378     }
4379 
4380     /* When item is inserted we need to shift existing focus index if new item has lower index. */
4381     if (isNew && (stateMask & ~infoPtr->uCallbackMask & LVIS_FOCUSED) &&
4382         /* this means we won't hit a focus change path later */
4383         ((uChanged & LVIF_STATE) == 0 || (!(lpLVItem->state & LVIS_FOCUSED) && (infoPtr->nFocusedItem != lpLVItem->iItem))))
4384     {
4385         if (infoPtr->nFocusedItem != -1 && (lpLVItem->iItem <= infoPtr->nFocusedItem))
4386             infoPtr->nFocusedItem++;
4387     }
4388 
4389     if (!uChanged) return TRUE;
4390     *bChanged = TRUE;
4391 
4392     /* copy information */
4393     if (lpLVItem->mask & LVIF_TEXT)
4394         textsetptrT(&lpItem->hdr.pszText, lpLVItem->pszText, isW);
4395 
4396     if (lpLVItem->mask & LVIF_IMAGE)
4397 	lpItem->hdr.iImage = lpLVItem->iImage;
4398 
4399     if (lpLVItem->mask & LVIF_PARAM)
4400 	lpItem->lParam = lpLVItem->lParam;
4401 
4402     if (lpLVItem->mask & LVIF_INDENT)
4403 	lpItem->iIndent = lpLVItem->iIndent;
4404 
4405     if (uChanged & LVIF_STATE)
4406     {
4407 	if (lpItem && (stateMask & ~infoPtr->uCallbackMask))
4408 	{
4409 	    lpItem->state &= ~stateMask;
4410 	    lpItem->state |= (lpLVItem->state & stateMask);
4411 	}
4412 	if (lpLVItem->state & stateMask & ~infoPtr->uCallbackMask & LVIS_SELECTED)
4413 	{
4414 	    if (infoPtr->dwStyle & LVS_SINGLESEL) LISTVIEW_DeselectAllSkipItem(infoPtr, lpLVItem->iItem);
4415 	    ranges_additem(infoPtr->selectionRanges, lpLVItem->iItem);
4416 	}
4417 	else if (stateMask & LVIS_SELECTED)
4418 	{
4419 	    ranges_delitem(infoPtr->selectionRanges, lpLVItem->iItem);
4420 	}
4421 	/* If we are asked to change focus, and we manage it, do it.
4422            It's important to have all new item data stored at this point,
4423            because changing existing focus could result in a redrawing operation,
4424            which in turn could ask for disp data, application should see all data
4425            for inserted item when processing LVN_GETDISPINFO.
4426 
4427            The way this works application will see nested item change notifications -
4428            changed item notifications interrupted by ones from item losing focus. */
4429 	if (stateMask & ~infoPtr->uCallbackMask & LVIS_FOCUSED)
4430 	{
4431 	    if (lpLVItem->state & LVIS_FOCUSED)
4432 	    {
4433 		/* update selection mark */
4434 		if (infoPtr->nFocusedItem == -1 && infoPtr->nSelectionMark == -1)
4435 		    infoPtr->nSelectionMark = lpLVItem->iItem;
4436 
4437 		if (infoPtr->nFocusedItem != -1)
4438 		{
4439 		    /* remove current focus */
4440 		    item.mask  = LVIF_STATE;
4441 		    item.state = 0;
4442 		    item.stateMask = LVIS_FOCUSED;
4443 
4444 		    /* recurse with redrawing an item */
4445 		    LISTVIEW_SetItemState(infoPtr, infoPtr->nFocusedItem, &item);
4446 		}
4447 
4448 		infoPtr->nFocusedItem = lpLVItem->iItem;
4449 	        LISTVIEW_EnsureVisible(infoPtr, lpLVItem->iItem, infoPtr->uView == LV_VIEW_LIST);
4450 	    }
4451 	    else if (infoPtr->nFocusedItem == lpLVItem->iItem)
4452 	    {
4453 	        infoPtr->nFocusedItem = -1;
4454 	    }
4455 	}
4456     }
4457 
4458     /* if we're inserting the item, we're done */
4459     if (isNew) return TRUE;
4460 
4461     /* send LVN_ITEMCHANGED notification */
4462     if (lpLVItem->mask & LVIF_PARAM) nmlv.lParam = lpLVItem->lParam;
4463     if (infoPtr->notify_mask & NOTIFY_MASK_ITEM_CHANGE)
4464         notify_listview(infoPtr, LVN_ITEMCHANGED, &nmlv);
4465 
4466     return TRUE;
4467 }
4468 
4469 /***
4470  * DESCRIPTION:
4471  * Helper for LISTVIEW_{Set,Insert}ItemT *only*: sets subitem attributes.
4472  *
4473  * PARAMETER(S):
4474  * [I] infoPtr : valid pointer to the listview structure
4475  * [I] lpLVItem : valid pointer to new subitem attributes
4476  * [I] isW : TRUE if lpLVItem is Unicode, FALSE if it's ANSI
4477  * [O] bChanged : will be set to TRUE if the item really changed
4478  *
4479  * RETURN:
4480  *   SUCCESS : TRUE
4481  *   FAILURE : FALSE
4482  */
4483 static BOOL set_sub_item(const LISTVIEW_INFO *infoPtr, const LVITEMW *lpLVItem, BOOL isW, BOOL *bChanged)
4484 {
4485     HDPA hdpaSubItems;
4486     SUBITEM_INFO *lpSubItem;
4487 
4488     /* we do not support subitems for virtual listviews */
4489     if (infoPtr->dwStyle & LVS_OWNERDATA) return FALSE;
4490 
4491     /* set subitem only if column is present */
4492     if (lpLVItem->iSubItem >= DPA_GetPtrCount(infoPtr->hdpaColumns)) return FALSE;
4493 
4494     /* First do some sanity checks */
4495     /* The LVIF_STATE flag is valid for subitems, but does not appear to be
4496        particularly useful. We currently do not actually do anything with
4497        the flag on subitems.
4498     */
4499     if (lpLVItem->mask & ~(LVIF_TEXT | LVIF_IMAGE | LVIF_STATE | LVIF_DI_SETITEM)) return FALSE;
4500     if (!(lpLVItem->mask & (LVIF_TEXT | LVIF_IMAGE | LVIF_STATE))) return TRUE;
4501 
4502     /* get the subitem structure, and create it if not there */
4503     hdpaSubItems = DPA_GetPtr(infoPtr->hdpaItems, lpLVItem->iItem);
4504     assert (hdpaSubItems);
4505 
4506     lpSubItem = LISTVIEW_GetSubItemPtr(hdpaSubItems, lpLVItem->iSubItem);
4507     if (!lpSubItem)
4508     {
4509 	SUBITEM_INFO *tmpSubItem;
4510 	INT i;
4511 
4512 	lpSubItem = Alloc(sizeof(SUBITEM_INFO));
4513 	if (!lpSubItem) return FALSE;
4514 	/* we could binary search here, if need be...*/
4515   	for (i = 1; i < DPA_GetPtrCount(hdpaSubItems); i++)
4516   	{
4517             tmpSubItem = DPA_GetPtr(hdpaSubItems, i);
4518 	    if (tmpSubItem->iSubItem > lpLVItem->iSubItem) break;
4519   	}
4520 	if (DPA_InsertPtr(hdpaSubItems, i, lpSubItem) == -1)
4521 	{
4522 	    Free(lpSubItem);
4523 	    return FALSE;
4524 	}
4525         lpSubItem->iSubItem = lpLVItem->iSubItem;
4526         lpSubItem->hdr.iImage = I_IMAGECALLBACK;
4527 	*bChanged = TRUE;
4528     }
4529 
4530     if ((lpLVItem->mask & LVIF_IMAGE) && (lpSubItem->hdr.iImage != lpLVItem->iImage))
4531     {
4532         lpSubItem->hdr.iImage = lpLVItem->iImage;
4533         *bChanged = TRUE;
4534     }
4535 
4536     if ((lpLVItem->mask & LVIF_TEXT) && textcmpWT(lpSubItem->hdr.pszText, lpLVItem->pszText, isW))
4537     {
4538         textsetptrT(&lpSubItem->hdr.pszText, lpLVItem->pszText, isW);
4539         *bChanged = TRUE;
4540     }
4541 
4542     return TRUE;
4543 }
4544 
4545 /***
4546  * DESCRIPTION:
4547  * Sets item attributes.
4548  *
4549  * PARAMETER(S):
4550  * [I] infoPtr : valid pointer to the listview structure
4551  * [I] lpLVItem : new item attributes
4552  * [I] isW : TRUE if lpLVItem is Unicode, FALSE if it's ANSI
4553  *
4554  * RETURN:
4555  *   SUCCESS : TRUE
4556  *   FAILURE : FALSE
4557  */
4558 static BOOL LISTVIEW_SetItemT(LISTVIEW_INFO *infoPtr, LVITEMW *lpLVItem, BOOL isW)
4559 {
4560     HWND hwndSelf = infoPtr->hwndSelf;
4561     LPWSTR pszText = NULL;
4562     BOOL bResult, bChanged = FALSE;
4563     RECT oldItemArea;
4564 
4565     TRACE("(lpLVItem=%s, isW=%d)\n", debuglvitem_t(lpLVItem, isW), isW);
4566 
4567     if (!lpLVItem || lpLVItem->iItem < 0 || lpLVItem->iItem >= infoPtr->nItemCount)
4568 	return FALSE;
4569 
4570     /* Store old item area */
4571     LISTVIEW_GetItemBox(infoPtr, lpLVItem->iItem, &oldItemArea);
4572 
4573     /* For efficiency, we transform the lpLVItem->pszText to Unicode here */
4574     if ((lpLVItem->mask & LVIF_TEXT) && is_text(lpLVItem->pszText))
4575     {
4576 	pszText = lpLVItem->pszText;
4577 	lpLVItem->pszText = textdupTtoW(lpLVItem->pszText, isW);
4578     }
4579 
4580     /* actually set the fields */
4581     if (!is_assignable_item(lpLVItem, infoPtr->dwStyle)) return FALSE;
4582 
4583     if (lpLVItem->iSubItem)
4584 	bResult = set_sub_item(infoPtr, lpLVItem, TRUE, &bChanged);
4585     else
4586 	bResult = set_main_item(infoPtr, lpLVItem, FALSE, TRUE, &bChanged);
4587     if (!IsWindow(hwndSelf))
4588 	return FALSE;
4589 
4590     /* redraw item, if necessary */
4591     if (bChanged && !infoPtr->bIsDrawing)
4592     {
4593 	/* this little optimization eliminates some nasty flicker */
4594 	if ( infoPtr->uView == LV_VIEW_DETAILS && !(infoPtr->dwStyle & LVS_OWNERDRAWFIXED) &&
4595 	     !(infoPtr->dwLvExStyle & LVS_EX_FULLROWSELECT) &&
4596              lpLVItem->iSubItem > 0 && lpLVItem->iSubItem <= DPA_GetPtrCount(infoPtr->hdpaColumns) )
4597 	    LISTVIEW_InvalidateSubItem(infoPtr, lpLVItem->iItem, lpLVItem->iSubItem);
4598 	else
4599         {
4600             LISTVIEW_InvalidateRect(infoPtr, &oldItemArea);
4601 	    LISTVIEW_InvalidateItem(infoPtr, lpLVItem->iItem);
4602         }
4603     }
4604     /* restore text */
4605     if (pszText)
4606     {
4607 	textfreeT(lpLVItem->pszText, isW);
4608 	lpLVItem->pszText = pszText;
4609     }
4610 
4611     return bResult;
4612 }
4613 
4614 /***
4615  * DESCRIPTION:
4616  * Retrieves the index of the item at coordinate (0, 0) of the client area.
4617  *
4618  * PARAMETER(S):
4619  * [I] infoPtr : valid pointer to the listview structure
4620  *
4621  * RETURN:
4622  * item index
4623  */
4624 static INT LISTVIEW_GetTopIndex(const LISTVIEW_INFO *infoPtr)
4625 {
4626     INT nItem = 0;
4627     SCROLLINFO scrollInfo;
4628 
4629     scrollInfo.cbSize = sizeof(SCROLLINFO);
4630     scrollInfo.fMask = SIF_POS;
4631 
4632     if (infoPtr->uView == LV_VIEW_LIST)
4633     {
4634 	if (GetScrollInfo(infoPtr->hwndSelf, SB_HORZ, &scrollInfo))
4635 	    nItem = scrollInfo.nPos * LISTVIEW_GetCountPerColumn(infoPtr);
4636     }
4637     else if (infoPtr->uView == LV_VIEW_DETAILS)
4638     {
4639 	if (GetScrollInfo(infoPtr->hwndSelf, SB_VERT, &scrollInfo))
4640 	    nItem = scrollInfo.nPos;
4641     }
4642     else
4643     {
4644 	if (GetScrollInfo(infoPtr->hwndSelf, SB_VERT, &scrollInfo))
4645 	    nItem = LISTVIEW_GetCountPerRow(infoPtr) * (scrollInfo.nPos / infoPtr->nItemHeight);
4646     }
4647 
4648     TRACE("nItem=%d\n", nItem);
4649 
4650     return nItem;
4651 }
4652 
4653 
4654 /***
4655  * DESCRIPTION:
4656  * Erases the background of the given rectangle
4657  *
4658  * PARAMETER(S):
4659  * [I] infoPtr : valid pointer to the listview structure
4660  * [I] hdc : device context handle
4661  * [I] lprcBox : clipping rectangle
4662  *
4663  * RETURN:
4664  *   Success: TRUE
4665  *   Failure: FALSE
4666  */
4667 static inline BOOL LISTVIEW_FillBkgnd(const LISTVIEW_INFO *infoPtr, HDC hdc, const RECT *lprcBox)
4668 {
4669     if (!infoPtr->hBkBrush) return FALSE;
4670 
4671     TRACE("(hdc=%p, lprcBox=%s, hBkBrush=%p)\n", hdc, wine_dbgstr_rect(lprcBox), infoPtr->hBkBrush);
4672 
4673     return FillRect(hdc, lprcBox, infoPtr->hBkBrush);
4674 }
4675 
4676 /* Draw main item or subitem */
4677 static void LISTVIEW_DrawItemPart(LISTVIEW_INFO *infoPtr, LVITEMW *item, const NMLVCUSTOMDRAW *nmlvcd, const POINT *pos)
4678 {
4679     RECT rcSelect, rcLabel, rcBox, rcStateIcon, rcIcon;
4680     const RECT *background;
4681     HIMAGELIST himl;
4682     UINT format;
4683     RECT *focus;
4684 
4685     /* now check if we need to update the focus rectangle */
4686     focus = infoPtr->bFocus && (item->state & LVIS_FOCUSED) ? &infoPtr->rcFocus : 0;
4687     if (!focus) item->state &= ~LVIS_FOCUSED;
4688 
4689     LISTVIEW_GetItemMetrics(infoPtr, item, &rcBox, &rcSelect, &rcIcon, &rcStateIcon, &rcLabel);
4690     OffsetRect(&rcBox, pos->x, pos->y);
4691     OffsetRect(&rcSelect, pos->x, pos->y);
4692     OffsetRect(&rcIcon, pos->x, pos->y);
4693     OffsetRect(&rcStateIcon, pos->x, pos->y);
4694     OffsetRect(&rcLabel, pos->x, pos->y);
4695     TRACE("%d: box=%s, select=%s, icon=%s. label=%s\n", item->iSubItem,
4696         wine_dbgstr_rect(&rcBox), wine_dbgstr_rect(&rcSelect),
4697         wine_dbgstr_rect(&rcIcon), wine_dbgstr_rect(&rcLabel));
4698 
4699     /* FIXME: temporary hack */
4700     rcSelect.left = rcLabel.left;
4701 
4702     if (infoPtr->uView == LV_VIEW_DETAILS && item->iSubItem == 0)
4703     {
4704         if (!(infoPtr->dwLvExStyle & LVS_EX_FULLROWSELECT))
4705             OffsetRect(&rcSelect, LISTVIEW_GetColumnInfo(infoPtr, 0)->rcHeader.left, 0);
4706         OffsetRect(&rcIcon, LISTVIEW_GetColumnInfo(infoPtr, 0)->rcHeader.left, 0);
4707         OffsetRect(&rcStateIcon, LISTVIEW_GetColumnInfo(infoPtr, 0)->rcHeader.left, 0);
4708         OffsetRect(&rcLabel, LISTVIEW_GetColumnInfo(infoPtr, 0)->rcHeader.left, 0);
4709     }
4710 
4711     /* in icon mode, the label rect is really what we want to draw the
4712      * background for */
4713     /* in detail mode, we want to paint background for label rect when
4714      * item is not selected or listview has full row select; otherwise paint
4715      * background for text only */
4716     if ( infoPtr->uView == LV_VIEW_ICON ||
4717         (infoPtr->uView == LV_VIEW_DETAILS && (!(item->state & LVIS_SELECTED) ||
4718         (infoPtr->dwLvExStyle & LVS_EX_FULLROWSELECT))))
4719         background = &rcLabel;
4720     else
4721         background = &rcSelect;
4722 
4723     if (nmlvcd->clrTextBk != CLR_NONE)
4724         ExtTextOutW(nmlvcd->nmcd.hdc, background->left, background->top, ETO_OPAQUE, background, NULL, 0, NULL);
4725 
4726     if (item->state & LVIS_FOCUSED)
4727     {
4728         if (infoPtr->uView == LV_VIEW_DETAILS)
4729         {
4730             if (infoPtr->dwLvExStyle & LVS_EX_FULLROWSELECT)
4731             {
4732                 /* we have to update left focus bound too if item isn't in leftmost column
4733 	           and reduce right box bound */
4734                 if (DPA_GetPtrCount(infoPtr->hdpaColumns) > 0)
4735                 {
4736                     INT leftmost;
4737 
4738                     if ((leftmost = SendMessageW(infoPtr->hwndHeader, HDM_ORDERTOINDEX, 0, 0)))
4739                     {
4740                         INT Originx = pos->x - LISTVIEW_GetColumnInfo(infoPtr, leftmost)->rcHeader.left;
4741                         INT rightmost = SendMessageW(infoPtr->hwndHeader, HDM_ORDERTOINDEX,
4742                             DPA_GetPtrCount(infoPtr->hdpaColumns) - 1, 0);
4743 
4744                         rcBox.right   = LISTVIEW_GetColumnInfo(infoPtr, rightmost)->rcHeader.right + Originx;
4745                         rcSelect.left = LISTVIEW_GetColumnInfo(infoPtr, leftmost)->rcHeader.left + Originx;
4746                     }
4747                 }
4748                 rcSelect.right = rcBox.right;
4749             }
4750             infoPtr->rcFocus = rcSelect;
4751         }
4752         else
4753             infoPtr->rcFocus = rcLabel;
4754     }
4755 
4756     /* state icons */
4757     if (infoPtr->himlState && STATEIMAGEINDEX(item->state) && (item->iSubItem == 0))
4758     {
4759         UINT stateimage = STATEIMAGEINDEX(item->state);
4760         if (stateimage)
4761 	{
4762 	     TRACE("stateimage=%d\n", stateimage);
4763 	     ImageList_Draw(infoPtr->himlState, stateimage-1, nmlvcd->nmcd.hdc, rcStateIcon.left, rcStateIcon.top, ILD_NORMAL);
4764 	}
4765     }
4766 
4767     /* item icons */
4768     himl = (infoPtr->uView == LV_VIEW_ICON ? infoPtr->himlNormal : infoPtr->himlSmall);
4769     if (himl && item->iImage >= 0 && !IsRectEmpty(&rcIcon))
4770     {
4771         UINT style;
4772 
4773         TRACE("iImage=%d\n", item->iImage);
4774 
4775         if (item->state & (LVIS_SELECTED | LVIS_CUT) && infoPtr->bFocus)
4776             style = ILD_SELECTED;
4777         else
4778             style = ILD_NORMAL;
4779 
4780         ImageList_DrawEx(himl, item->iImage, nmlvcd->nmcd.hdc, rcIcon.left, rcIcon.top,
4781                          rcIcon.right - rcIcon.left, rcIcon.bottom - rcIcon.top, infoPtr->clrBk,
4782                          item->state & LVIS_CUT ? RGB(255, 255, 255) : CLR_DEFAULT,
4783                          style | (item->state & LVIS_OVERLAYMASK));
4784     }
4785 
4786     /* Don't bother painting item being edited */
4787     if (infoPtr->hwndEdit && item->iItem == infoPtr->nEditLabelItem && item->iSubItem == 0) return;
4788 
4789     /* figure out the text drawing flags */
4790     format = (infoPtr->uView == LV_VIEW_ICON ? (focus ? LV_FL_DT_FLAGS : LV_ML_DT_FLAGS) : LV_SL_DT_FLAGS);
4791     if (infoPtr->uView == LV_VIEW_ICON)
4792 	format = (focus ? LV_FL_DT_FLAGS : LV_ML_DT_FLAGS);
4793     else if (item->iSubItem)
4794     {
4795 	switch (LISTVIEW_GetColumnInfo(infoPtr, item->iSubItem)->fmt & LVCFMT_JUSTIFYMASK)
4796 	{
4797 	case LVCFMT_RIGHT:  format |= DT_RIGHT;  break;
4798 	case LVCFMT_CENTER: format |= DT_CENTER; break;
4799 	default:            format |= DT_LEFT;
4800 	}
4801     }
4802     if (!(format & (DT_RIGHT | DT_CENTER)))
4803     {
4804         if (himl && item->iImage >= 0 && !IsRectEmpty(&rcIcon)) rcLabel.left += IMAGE_PADDING;
4805         else rcLabel.left += LABEL_HOR_PADDING;
4806     }
4807     else if (format & DT_RIGHT) rcLabel.right -= LABEL_HOR_PADDING;
4808 
4809     /* for GRIDLINES reduce the bottom so the text formats correctly */
4810     if (infoPtr->uView == LV_VIEW_DETAILS && infoPtr->dwLvExStyle & LVS_EX_GRIDLINES)
4811         rcLabel.bottom--;
4812 
4813 #ifdef __REACTOS__
4814     if ((!(item->state & LVIS_SELECTED) || !infoPtr->bFocus) && (infoPtr->dwLvExStyle & LVS_EX_TRANSPARENTSHADOWTEXT))
4815         DrawShadowText(nmlvcd->nmcd.hdc, item->pszText, -1, &rcLabel, format, RGB(255, 255, 255), RGB(0, 0, 0), 2, 2);
4816     else
4817 #endif
4818         DrawTextW(nmlvcd->nmcd.hdc, item->pszText, -1, &rcLabel, format);
4819 }
4820 
4821 /***
4822  * DESCRIPTION:
4823  * Draws an item.
4824  *
4825  * PARAMETER(S):
4826  * [I] infoPtr : valid pointer to the listview structure
4827  * [I] hdc : device context handle
4828  * [I] nItem : item index
4829  * [I] nSubItem : subitem index
4830  * [I] pos : item position in client coordinates
4831  * [I] cdmode : custom draw mode
4832  *
4833  * RETURN:
4834  *   Success: TRUE
4835  *   Failure: FALSE
4836  */
4837 static BOOL LISTVIEW_DrawItem(LISTVIEW_INFO *infoPtr, HDC hdc, INT nItem, ITERATOR *subitems, POINT pos, DWORD cdmode)
4838 {
4839     WCHAR szDispText[DISP_TEXT_SIZE] = { '\0' };
4840     static WCHAR callbackW[] = { '(', 'c', 'a', 'l', 'l', 'b', 'a', 'c', 'k', ')', 0 };
4841     DWORD cdsubitemmode = CDRF_DODEFAULT;
4842     RECT *focus, rcBox;
4843     NMLVCUSTOMDRAW nmlvcd;
4844     LVITEMW lvItem;
4845 
4846     TRACE("(hdc=%p, nItem=%d, subitems=%p, pos=%s)\n", hdc, nItem, subitems, wine_dbgstr_point(&pos));
4847 
4848     /* get information needed for drawing the item */
4849     lvItem.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_PARAM | LVIF_STATE;
4850     if (infoPtr->uView == LV_VIEW_DETAILS) lvItem.mask |= LVIF_INDENT;
4851     lvItem.stateMask = LVIS_SELECTED | LVIS_FOCUSED | LVIS_STATEIMAGEMASK | LVIS_CUT | LVIS_OVERLAYMASK;
4852     lvItem.iItem = nItem;
4853     lvItem.iSubItem = 0;
4854     lvItem.state = 0;
4855     lvItem.lParam = 0;
4856     lvItem.cchTextMax = DISP_TEXT_SIZE;
4857     lvItem.pszText = szDispText;
4858     if (!LISTVIEW_GetItemW(infoPtr, &lvItem)) return FALSE;
4859     if (lvItem.pszText == LPSTR_TEXTCALLBACKW) lvItem.pszText = callbackW;
4860     TRACE("   lvItem=%s\n", debuglvitem_t(&lvItem, TRUE));
4861 
4862     /* now check if we need to update the focus rectangle */
4863     focus = infoPtr->bFocus && (lvItem.state & LVIS_FOCUSED) ? &infoPtr->rcFocus : 0;
4864     if (!focus) lvItem.state &= ~LVIS_FOCUSED;
4865 
4866     LISTVIEW_GetItemMetrics(infoPtr, &lvItem, &rcBox, NULL, NULL, NULL, NULL);
4867     OffsetRect(&rcBox, pos.x, pos.y);
4868 
4869     /* Full custom draw stage sequence looks like this:
4870 
4871        LV_VIEW_DETAILS:
4872 
4873        - CDDS_ITEMPREPAINT
4874        - CDDS_ITEMPREPAINT|CDDS_SUBITEM   | => sent n times, where n is number of subitems,
4875          CDDS_ITEMPOSTPAINT|CDDS_SUBITEM  |    including item itself
4876        - CDDS_ITEMPOSTPAINT
4877 
4878        other styles:
4879 
4880        - CDDS_ITEMPREPAINT
4881        - CDDS_ITEMPOSTPAINT
4882     */
4883 
4884     /* fill in the custom draw structure */
4885     customdraw_fill(&nmlvcd, infoPtr, hdc, &rcBox, &lvItem);
4886     if (cdmode & CDRF_NOTIFYITEMDRAW)
4887         cdsubitemmode = notify_customdraw(infoPtr, CDDS_ITEMPREPAINT, &nmlvcd);
4888     if (cdsubitemmode & CDRF_SKIPDEFAULT) goto postpaint;
4889 
4890     if (subitems)
4891     {
4892         while (iterator_next(subitems))
4893         {
4894             DWORD subitemstage = CDRF_DODEFAULT;
4895             NMLVCUSTOMDRAW temp_nmlvcd;
4896 
4897             /* We need to query for each subitem, item's data (subitem == 0) is already here at this point */
4898             if (subitems->nItem)
4899             {
4900                 lvItem.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_PARAM | LVIF_INDENT;
4901                 lvItem.stateMask = LVIS_SELECTED | LVIS_FOCUSED | LVIS_STATEIMAGEMASK | LVIS_CUT | LVIS_OVERLAYMASK;
4902                 lvItem.iItem = nItem;
4903                 lvItem.iSubItem = subitems->nItem;
4904                 lvItem.state = 0;
4905                 lvItem.lParam = 0;
4906                 lvItem.cchTextMax = DISP_TEXT_SIZE;
4907                 lvItem.pszText = szDispText;
4908                 if (!LISTVIEW_GetItemW(infoPtr, &lvItem)) return FALSE;
4909                 if (infoPtr->dwLvExStyle & LVS_EX_FULLROWSELECT)
4910 	            lvItem.state = LISTVIEW_GetItemState(infoPtr, nItem, LVIS_SELECTED);
4911                 if (lvItem.pszText == LPSTR_TEXTCALLBACKW) lvItem.pszText = callbackW;
4912                 TRACE("   lvItem=%s\n", debuglvitem_t(&lvItem, TRUE));
4913 
4914                 /* update custom draw data */
4915                 LISTVIEW_GetItemMetrics(infoPtr, &lvItem, &nmlvcd.nmcd.rc, NULL, NULL, NULL, NULL);
4916                 OffsetRect(&nmlvcd.nmcd.rc, pos.x, pos.y);
4917                 nmlvcd.iSubItem = subitems->nItem;
4918             }
4919 
4920             if (cdsubitemmode & CDRF_NOTIFYSUBITEMDRAW)
4921                 subitemstage = notify_customdraw(infoPtr, CDDS_SUBITEM | CDDS_ITEMPREPAINT, &nmlvcd);
4922 
4923             /*
4924              * A selection should neither affect the colors in the post paint notification nor
4925              * affect the colors of the next drawn subitem. Copy the structure to prevent this.
4926              */
4927             temp_nmlvcd = nmlvcd;
4928             prepaint_setup(infoPtr, hdc, &temp_nmlvcd, subitems->nItem);
4929 
4930             if (!(subitemstage & CDRF_SKIPDEFAULT))
4931                 LISTVIEW_DrawItemPart(infoPtr, &lvItem, &temp_nmlvcd, &pos);
4932 
4933             if (subitemstage & CDRF_NOTIFYPOSTPAINT)
4934                 subitemstage = notify_customdraw(infoPtr, CDDS_SUBITEM | CDDS_ITEMPOSTPAINT, &nmlvcd);
4935         }
4936     }
4937     else
4938     {
4939         prepaint_setup(infoPtr, hdc, &nmlvcd, FALSE);
4940         LISTVIEW_DrawItemPart(infoPtr, &lvItem, &nmlvcd, &pos);
4941     }
4942 
4943 postpaint:
4944     if (cdsubitemmode & CDRF_NOTIFYPOSTPAINT)
4945     {
4946         nmlvcd.iSubItem = 0;
4947         notify_customdraw(infoPtr, CDDS_ITEMPOSTPAINT, &nmlvcd);
4948     }
4949 
4950     return TRUE;
4951 }
4952 
4953 /***
4954  * DESCRIPTION:
4955  * Draws listview items when in owner draw mode.
4956  *
4957  * PARAMETER(S):
4958  * [I] infoPtr : valid pointer to the listview structure
4959  * [I] hdc : device context handle
4960  *
4961  * RETURN:
4962  * None
4963  */
4964 static void LISTVIEW_RefreshOwnerDraw(const LISTVIEW_INFO *infoPtr, ITERATOR *i, HDC hdc, DWORD cdmode)
4965 {
4966     UINT uID = (UINT)GetWindowLongPtrW(infoPtr->hwndSelf, GWLP_ID);
4967     DWORD cditemmode = CDRF_DODEFAULT;
4968     NMLVCUSTOMDRAW nmlvcd;
4969     POINT Origin, Position;
4970     DRAWITEMSTRUCT dis;
4971     LVITEMW item;
4972 
4973     TRACE("()\n");
4974 
4975     ZeroMemory(&dis, sizeof(dis));
4976 
4977     /* Get scroll info once before loop */
4978     LISTVIEW_GetOrigin(infoPtr, &Origin);
4979 
4980     /* iterate through the invalidated rows */
4981     while(iterator_next(i))
4982     {
4983 	item.iItem = i->nItem;
4984 	item.iSubItem = 0;
4985 	item.mask = LVIF_PARAM | LVIF_STATE;
4986 	item.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
4987 	if (!LISTVIEW_GetItemW(infoPtr, &item)) continue;
4988 
4989 	dis.CtlType = ODT_LISTVIEW;
4990 	dis.CtlID = uID;
4991 	dis.itemID = item.iItem;
4992 	dis.itemAction = ODA_DRAWENTIRE;
4993 	dis.itemState = 0;
4994 	if (item.state & LVIS_SELECTED) dis.itemState |= ODS_SELECTED;
4995 	if (infoPtr->bFocus && (item.state & LVIS_FOCUSED)) dis.itemState |= ODS_FOCUS;
4996 	dis.hwndItem = infoPtr->hwndSelf;
4997 	dis.hDC = hdc;
4998 	LISTVIEW_GetItemOrigin(infoPtr, dis.itemID, &Position);
4999 	dis.rcItem.left = Position.x + Origin.x;
5000 	dis.rcItem.right = dis.rcItem.left + infoPtr->nItemWidth;
5001 	dis.rcItem.top = Position.y + Origin.y;
5002 	dis.rcItem.bottom = dis.rcItem.top + infoPtr->nItemHeight;
5003 	dis.itemData = item.lParam;
5004 
5005 	TRACE("item=%s, rcItem=%s\n", debuglvitem_t(&item, TRUE), wine_dbgstr_rect(&dis.rcItem));
5006 
5007     /*
5008      * Even if we do not send the CDRF_NOTIFYITEMDRAW we need to fill the nmlvcd
5009      * structure for the rest. of the paint cycle
5010      */
5011 	customdraw_fill(&nmlvcd, infoPtr, hdc, &dis.rcItem, &item);
5012 	if (cdmode & CDRF_NOTIFYITEMDRAW)
5013             cditemmode = notify_customdraw(infoPtr, CDDS_PREPAINT, &nmlvcd);
5014 
5015 	if (!(cditemmode & CDRF_SKIPDEFAULT))
5016 	{
5017             prepaint_setup (infoPtr, hdc, &nmlvcd, FALSE);
5018 	    SendMessageW(infoPtr->hwndNotify, WM_DRAWITEM, dis.CtlID, (LPARAM)&dis);
5019 	}
5020 
5021     	if (cditemmode & CDRF_NOTIFYPOSTPAINT)
5022             notify_postpaint(infoPtr, &nmlvcd);
5023     }
5024 }
5025 
5026 /***
5027  * DESCRIPTION:
5028  * Draws listview items when in report display mode.
5029  *
5030  * PARAMETER(S):
5031  * [I] infoPtr : valid pointer to the listview structure
5032  * [I] hdc : device context handle
5033  * [I] cdmode : custom draw mode
5034  *
5035  * RETURN:
5036  * None
5037  */
5038 static void LISTVIEW_RefreshReport(LISTVIEW_INFO *infoPtr, ITERATOR *i, HDC hdc, DWORD cdmode)
5039 {
5040     INT rgntype;
5041     RECT rcClip, rcItem;
5042     POINT Origin;
5043     RANGES colRanges;
5044     INT col;
5045     ITERATOR j;
5046 
5047     TRACE("()\n");
5048 
5049     /* figure out what to draw */
5050     rgntype = GetClipBox(hdc, &rcClip);
5051     if (rgntype == NULLREGION) return;
5052 
5053     /* Get scroll info once before loop */
5054     LISTVIEW_GetOrigin(infoPtr, &Origin);
5055 
5056     colRanges = ranges_create(DPA_GetPtrCount(infoPtr->hdpaColumns));
5057 
5058     /* narrow down the columns we need to paint */
5059     for(col = 0; col < DPA_GetPtrCount(infoPtr->hdpaColumns); col++)
5060     {
5061 	INT index = SendMessageW(infoPtr->hwndHeader, HDM_ORDERTOINDEX, col, 0);
5062 
5063 	LISTVIEW_GetHeaderRect(infoPtr, index, &rcItem);
5064 	if ((rcItem.right + Origin.x >= rcClip.left) && (rcItem.left + Origin.x < rcClip.right))
5065 	    ranges_additem(colRanges, index);
5066     }
5067     iterator_rangesitems(&j, colRanges);
5068 
5069     /* in full row select, we _have_ to draw the main item */
5070     if (infoPtr->dwLvExStyle & LVS_EX_FULLROWSELECT)
5071 	j.nSpecial = 0;
5072 
5073     /* iterate through the invalidated rows */
5074     while(iterator_next(i))
5075     {
5076         RANGES subitems;
5077         POINT Position;
5078         ITERATOR k;
5079 
5080         SelectObject(hdc, infoPtr->hFont);
5081 	LISTVIEW_GetItemOrigin(infoPtr, i->nItem, &Position);
5082         Position.x = Origin.x;
5083 	Position.y += Origin.y;
5084 
5085         subitems = ranges_create(DPA_GetPtrCount(infoPtr->hdpaColumns));
5086 
5087 	/* iterate through the invalidated columns */
5088 	while(iterator_next(&j))
5089 	{
5090 	    LISTVIEW_GetHeaderRect(infoPtr, j.nItem, &rcItem);
5091 
5092 	    if (rgntype == COMPLEXREGION && !((infoPtr->dwLvExStyle & LVS_EX_FULLROWSELECT) && j.nItem == 0))
5093 	    {
5094 		rcItem.top = 0;
5095 	        rcItem.bottom = infoPtr->nItemHeight;
5096 		OffsetRect(&rcItem, Origin.x, Position.y);
5097 		if (!RectVisible(hdc, &rcItem)) continue;
5098 	    }
5099 
5100             ranges_additem(subitems, j.nItem);
5101 	}
5102 
5103         iterator_rangesitems(&k, subitems);
5104         LISTVIEW_DrawItem(infoPtr, hdc, i->nItem, &k, Position, cdmode);
5105         iterator_destroy(&k);
5106     }
5107     iterator_destroy(&j);
5108 }
5109 
5110 /***
5111  * DESCRIPTION:
5112  * Draws the gridlines if necessary when in report display mode.
5113  *
5114  * PARAMETER(S):
5115  * [I] infoPtr : valid pointer to the listview structure
5116  * [I] hdc : device context handle
5117  *
5118  * RETURN:
5119  * None
5120  */
5121 static void LISTVIEW_RefreshReportGrid(LISTVIEW_INFO *infoPtr, HDC hdc)
5122 {
5123     INT rgntype;
5124     INT y, itemheight;
5125     INT col, index;
5126     HPEN hPen, hOldPen;
5127     RECT rcClip, rcItem = {0};
5128     POINT Origin;
5129     RANGES colRanges;
5130     ITERATOR j;
5131     BOOL rmost = FALSE;
5132 
5133     TRACE("()\n");
5134 
5135     /* figure out what to draw */
5136     rgntype = GetClipBox(hdc, &rcClip);
5137     if (rgntype == NULLREGION) return;
5138 
5139     /* Get scroll info once before loop */
5140     LISTVIEW_GetOrigin(infoPtr, &Origin);
5141 
5142     colRanges = ranges_create(DPA_GetPtrCount(infoPtr->hdpaColumns));
5143 
5144     /* narrow down the columns we need to paint */
5145     for(col = 0; col < DPA_GetPtrCount(infoPtr->hdpaColumns); col++)
5146     {
5147         index = SendMessageW(infoPtr->hwndHeader, HDM_ORDERTOINDEX, col, 0);
5148 
5149         LISTVIEW_GetHeaderRect(infoPtr, index, &rcItem);
5150         if ((rcItem.right + Origin.x >= rcClip.left) && (rcItem.left + Origin.x < rcClip.right))
5151             ranges_additem(colRanges, index);
5152     }
5153 
5154     /* is right most vertical line visible? */
5155     if (DPA_GetPtrCount(infoPtr->hdpaColumns) > 0)
5156     {
5157         index = SendMessageW(infoPtr->hwndHeader, HDM_ORDERTOINDEX, DPA_GetPtrCount(infoPtr->hdpaColumns) - 1, 0);
5158         LISTVIEW_GetHeaderRect(infoPtr, index, &rcItem);
5159         rmost = (rcItem.right + Origin.x < rcClip.right);
5160     }
5161 
5162     if ((hPen = CreatePen( PS_SOLID, 1, comctl32_color.clr3dFace )))
5163     {
5164         hOldPen = SelectObject ( hdc, hPen );
5165 
5166         /* draw the vertical lines for the columns */
5167         iterator_rangesitems(&j, colRanges);
5168         while(iterator_next(&j))
5169         {
5170             LISTVIEW_GetHeaderRect(infoPtr, j.nItem, &rcItem);
5171             if (rcItem.left == 0) continue; /* skip leftmost column */
5172             rcItem.left += Origin.x;
5173             rcItem.right += Origin.x;
5174             rcItem.top = infoPtr->rcList.top;
5175             rcItem.bottom = infoPtr->rcList.bottom;
5176             TRACE("vert col=%d, rcItem=%s\n", j.nItem, wine_dbgstr_rect(&rcItem));
5177             MoveToEx (hdc, rcItem.left, rcItem.top, NULL);
5178             LineTo (hdc, rcItem.left, rcItem.bottom);
5179         }
5180         iterator_destroy(&j);
5181         /* draw rightmost grid line if visible */
5182         if (rmost)
5183         {
5184             index = SendMessageW(infoPtr->hwndHeader, HDM_ORDERTOINDEX,
5185                                  DPA_GetPtrCount(infoPtr->hdpaColumns) - 1, 0);
5186             LISTVIEW_GetHeaderRect(infoPtr, index, &rcItem);
5187 
5188             rcItem.right += Origin.x;
5189 
5190             MoveToEx (hdc, rcItem.right, infoPtr->rcList.top, NULL);
5191             LineTo (hdc, rcItem.right, infoPtr->rcList.bottom);
5192         }
5193 
5194         /* draw the horizontal lines for the rows */
5195         itemheight =  LISTVIEW_CalculateItemHeight(infoPtr);
5196         rcItem.left   = infoPtr->rcList.left;
5197         rcItem.right  = infoPtr->rcList.right;
5198         for(y = Origin.y > 1 ? Origin.y - 1 : itemheight - 1 + Origin.y % itemheight; y<=infoPtr->rcList.bottom; y+=itemheight)
5199         {
5200             rcItem.bottom = rcItem.top = y;
5201             TRACE("horz rcItem=%s\n", wine_dbgstr_rect(&rcItem));
5202             MoveToEx (hdc, rcItem.left, rcItem.top, NULL);
5203             LineTo (hdc, rcItem.right, rcItem.top);
5204         }
5205 
5206         SelectObject( hdc, hOldPen );
5207         DeleteObject( hPen );
5208     }
5209     else
5210         ranges_destroy(colRanges);
5211 }
5212 
5213 /***
5214  * DESCRIPTION:
5215  * Draws listview items when in list display mode.
5216  *
5217  * PARAMETER(S):
5218  * [I] infoPtr : valid pointer to the listview structure
5219  * [I] hdc : device context handle
5220  * [I] cdmode : custom draw mode
5221  *
5222  * RETURN:
5223  * None
5224  */
5225 static void LISTVIEW_RefreshList(LISTVIEW_INFO *infoPtr, ITERATOR *i, HDC hdc, DWORD cdmode)
5226 {
5227     POINT Origin, Position;
5228 
5229     /* Get scroll info once before loop */
5230     LISTVIEW_GetOrigin(infoPtr, &Origin);
5231 
5232     while(iterator_prev(i))
5233     {
5234         SelectObject(hdc, infoPtr->hFont);
5235 	LISTVIEW_GetItemOrigin(infoPtr, i->nItem, &Position);
5236 	Position.x += Origin.x;
5237 	Position.y += Origin.y;
5238 
5239         LISTVIEW_DrawItem(infoPtr, hdc, i->nItem, NULL, Position, cdmode);
5240     }
5241 }
5242 
5243 
5244 /***
5245  * DESCRIPTION:
5246  * Draws listview items.
5247  *
5248  * PARAMETER(S):
5249  * [I] infoPtr : valid pointer to the listview structure
5250  * [I] hdc : device context handle
5251  * [I] prcErase : rect to be erased before refresh (may be NULL)
5252  *
5253  * RETURN:
5254  * NoneX
5255  */
5256 static void LISTVIEW_Refresh(LISTVIEW_INFO *infoPtr, HDC hdc, const RECT *prcErase)
5257 {
5258     COLORREF oldTextColor = 0, oldBkColor = 0;
5259     NMLVCUSTOMDRAW nmlvcd;
5260     HFONT hOldFont = 0;
5261     DWORD cdmode;
5262     INT oldBkMode = 0;
5263     RECT rcClient;
5264     ITERATOR i;
5265     HDC hdcOrig = hdc;
5266     HBITMAP hbmp = NULL;
5267     RANGE range;
5268 
5269     LISTVIEW_DUMP(infoPtr);
5270 
5271     if (infoPtr->dwLvExStyle & LVS_EX_DOUBLEBUFFER) {
5272         TRACE("double buffering\n");
5273 
5274         hdc = CreateCompatibleDC(hdcOrig);
5275         if (!hdc) {
5276             ERR("Failed to create DC for backbuffer\n");
5277             return;
5278         }
5279         hbmp = CreateCompatibleBitmap(hdcOrig, infoPtr->rcList.right,
5280                                       infoPtr->rcList.bottom);
5281         if (!hbmp) {
5282             ERR("Failed to create bitmap for backbuffer\n");
5283             DeleteDC(hdc);
5284             return;
5285         }
5286 
5287         SelectObject(hdc, hbmp);
5288         SelectObject(hdc, infoPtr->hFont);
5289 
5290         if(GetClipBox(hdcOrig, &rcClient))
5291             IntersectClipRect(hdc, rcClient.left, rcClient.top, rcClient.right, rcClient.bottom);
5292     } else {
5293         /* Save dc values we're gonna trash while drawing
5294          * FIXME: Should be done in LISTVIEW_DrawItem() */
5295         hOldFont = SelectObject(hdc, infoPtr->hFont);
5296         oldBkMode = GetBkMode(hdc);
5297         oldBkColor = GetBkColor(hdc);
5298         oldTextColor = GetTextColor(hdc);
5299     }
5300 
5301     infoPtr->bIsDrawing = TRUE;
5302 
5303     if (prcErase) {
5304         LISTVIEW_FillBkgnd(infoPtr, hdc, prcErase);
5305     } else if (infoPtr->dwLvExStyle & LVS_EX_DOUBLEBUFFER) {
5306         /* If no erasing was done (usually because RedrawWindow was called
5307          * with RDW_INVALIDATE only) we need to copy the old contents into
5308          * the backbuffer before continuing. */
5309         BitBlt(hdc, infoPtr->rcList.left, infoPtr->rcList.top,
5310                infoPtr->rcList.right - infoPtr->rcList.left,
5311                infoPtr->rcList.bottom - infoPtr->rcList.top,
5312                hdcOrig, infoPtr->rcList.left, infoPtr->rcList.top, SRCCOPY);
5313     }
5314 
5315     GetClientRect(infoPtr->hwndSelf, &rcClient);
5316     customdraw_fill(&nmlvcd, infoPtr, hdc, &rcClient, 0);
5317     cdmode = notify_customdraw(infoPtr, CDDS_PREPAINT, &nmlvcd);
5318     if (cdmode & CDRF_SKIPDEFAULT) goto enddraw;
5319 
5320     /* nothing to draw */
5321     if(infoPtr->nItemCount == 0) goto enddraw;
5322 
5323     /* figure out what we need to draw */
5324     iterator_visibleitems(&i, infoPtr, hdc);
5325     range = iterator_range(&i);
5326 
5327     /* send cache hint notification */
5328     if (infoPtr->dwStyle & LVS_OWNERDATA)
5329     {
5330 	NMLVCACHEHINT nmlv;
5331 
5332     	ZeroMemory(&nmlv, sizeof(NMLVCACHEHINT));
5333     	nmlv.iFrom = range.lower;
5334     	nmlv.iTo   = range.upper - 1;
5335     	notify_hdr(infoPtr, LVN_ODCACHEHINT, &nmlv.hdr);
5336     }
5337 
5338     if ((infoPtr->dwStyle & LVS_OWNERDRAWFIXED) && (infoPtr->uView == LV_VIEW_DETAILS))
5339 	LISTVIEW_RefreshOwnerDraw(infoPtr, &i, hdc, cdmode);
5340     else
5341     {
5342 	if (infoPtr->uView == LV_VIEW_DETAILS)
5343             LISTVIEW_RefreshReport(infoPtr, &i, hdc, cdmode);
5344 	else /* LV_VIEW_LIST, LV_VIEW_ICON or LV_VIEW_SMALLICON */
5345 	    LISTVIEW_RefreshList(infoPtr, &i, hdc, cdmode);
5346 
5347 	/* if we have a focus rect and it's visible, draw it */
5348 	if (infoPtr->bFocus && range.lower <= infoPtr->nFocusedItem &&
5349                         (range.upper - 1) >= infoPtr->nFocusedItem)
5350 	    LISTVIEW_DrawFocusRect(infoPtr, hdc);
5351     }
5352     iterator_destroy(&i);
5353 
5354 enddraw:
5355     /* For LVS_EX_GRIDLINES go and draw lines */
5356     /*  This includes the case where there were *no* items */
5357     if ((infoPtr->uView == LV_VIEW_DETAILS) && infoPtr->dwLvExStyle & LVS_EX_GRIDLINES)
5358         LISTVIEW_RefreshReportGrid(infoPtr, hdc);
5359 
5360     /* Draw marquee rectangle if appropriate */
5361     if (infoPtr->bMarqueeSelect)
5362 #ifdef __REACTOS__
5363     {
5364         SetBkColor(hdc, RGB(255, 255, 255));
5365         SetTextColor(hdc, RGB(0, 0, 0));
5366         DrawFocusRect(hdc, &infoPtr->marqueeDrawRect);
5367     }
5368 #else
5369         DrawFocusRect(hdc, &infoPtr->marqueeDrawRect);
5370 #endif
5371 
5372     if (cdmode & CDRF_NOTIFYPOSTPAINT)
5373 	notify_postpaint(infoPtr, &nmlvcd);
5374 
5375     if(hbmp) {
5376         BitBlt(hdcOrig, infoPtr->rcList.left, infoPtr->rcList.top,
5377                infoPtr->rcList.right - infoPtr->rcList.left,
5378                infoPtr->rcList.bottom - infoPtr->rcList.top,
5379                hdc, infoPtr->rcList.left, infoPtr->rcList.top, SRCCOPY);
5380 
5381         DeleteObject(hbmp);
5382         DeleteDC(hdc);
5383     } else {
5384         SelectObject(hdc, hOldFont);
5385         SetBkMode(hdc, oldBkMode);
5386         SetBkColor(hdc, oldBkColor);
5387         SetTextColor(hdc, oldTextColor);
5388     }
5389 
5390     infoPtr->bIsDrawing = FALSE;
5391 }
5392 
5393 
5394 /***
5395  * DESCRIPTION:
5396  * Calculates the approximate width and height of a given number of items.
5397  *
5398  * PARAMETER(S):
5399  * [I] infoPtr : valid pointer to the listview structure
5400  * [I] nItemCount : number of items
5401  * [I] wWidth : width
5402  * [I] wHeight : height
5403  *
5404  * RETURN:
5405  * Returns a DWORD. The width in the low word and the height in high word.
5406  */
5407 static DWORD LISTVIEW_ApproximateViewRect(const LISTVIEW_INFO *infoPtr, INT nItemCount,
5408                                             WORD wWidth, WORD wHeight)
5409 {
5410   DWORD dwViewRect = 0;
5411 
5412   if (nItemCount == -1)
5413     nItemCount = infoPtr->nItemCount;
5414 
5415   if (infoPtr->uView == LV_VIEW_LIST)
5416   {
5417     INT nItemCountPerColumn = 1;
5418     INT nColumnCount = 0;
5419 
5420     if (wHeight == 0xFFFF)
5421     {
5422       /* use current height */
5423       wHeight = infoPtr->rcList.bottom - infoPtr->rcList.top;
5424     }
5425 
5426     if (wHeight < infoPtr->nItemHeight)
5427       wHeight = infoPtr->nItemHeight;
5428 
5429     if (nItemCount > 0)
5430     {
5431       if (infoPtr->nItemHeight > 0)
5432       {
5433         nItemCountPerColumn = wHeight / infoPtr->nItemHeight;
5434         if (nItemCountPerColumn == 0)
5435           nItemCountPerColumn = 1;
5436 
5437         if (nItemCount % nItemCountPerColumn != 0)
5438           nColumnCount = nItemCount / nItemCountPerColumn;
5439         else
5440           nColumnCount = nItemCount / nItemCountPerColumn + 1;
5441       }
5442     }
5443 
5444     /* Microsoft padding magic */
5445     wHeight = nItemCountPerColumn * infoPtr->nItemHeight + 2;
5446     wWidth = nColumnCount * infoPtr->nItemWidth + 2;
5447 
5448     dwViewRect = MAKELONG(wWidth, wHeight);
5449   }
5450   else if (infoPtr->uView == LV_VIEW_DETAILS)
5451   {
5452     RECT rcBox;
5453 
5454     if (infoPtr->nItemCount > 0)
5455     {
5456       LISTVIEW_GetItemBox(infoPtr, 0, &rcBox);
5457       wWidth = rcBox.right - rcBox.left;
5458       wHeight = (rcBox.bottom - rcBox.top) * nItemCount;
5459     }
5460     else
5461     {
5462       /* use current height and width */
5463       if (wHeight == 0xffff)
5464           wHeight = infoPtr->rcList.bottom - infoPtr->rcList.top;
5465       if (wWidth == 0xffff)
5466           wWidth = infoPtr->rcList.right - infoPtr->rcList.left;
5467     }
5468 
5469     dwViewRect = MAKELONG(wWidth, wHeight);
5470   }
5471   else if (infoPtr->uView == LV_VIEW_ICON)
5472   {
5473     UINT rows,cols;
5474     UINT nItemWidth;
5475     UINT nItemHeight;
5476 
5477     nItemWidth = infoPtr->iconSpacing.cx;
5478     nItemHeight = infoPtr->iconSpacing.cy;
5479 
5480     if (wWidth == 0xffff)
5481       wWidth = infoPtr->rcList.right - infoPtr->rcList.left;
5482 
5483     if (wWidth < nItemWidth)
5484       wWidth = nItemWidth;
5485 
5486     cols = wWidth / nItemWidth;
5487     if (cols > nItemCount)
5488       cols = nItemCount;
5489     if (cols < 1)
5490         cols = 1;
5491 
5492     if (nItemCount)
5493     {
5494       rows = nItemCount / cols;
5495       if (nItemCount % cols)
5496         rows++;
5497     }
5498     else
5499       rows = 0;
5500 
5501     wHeight = (nItemHeight * rows)+2;
5502     wWidth = (nItemWidth * cols)+2;
5503 
5504     dwViewRect = MAKELONG(wWidth, wHeight);
5505   }
5506   else if (infoPtr->uView == LV_VIEW_SMALLICON)
5507     FIXME("uView == LV_VIEW_SMALLICON: not implemented\n");
5508 
5509   return dwViewRect;
5510 }
5511 
5512 /***
5513  * DESCRIPTION:
5514  * Cancel edit label with saving item text.
5515  *
5516  * PARAMETER(S):
5517  * [I] infoPtr : valid pointer to the listview structure
5518  *
5519  * RETURN:
5520  * Always returns TRUE.
5521  */
5522 static LRESULT LISTVIEW_CancelEditLabel(LISTVIEW_INFO *infoPtr)
5523 {
5524     if (infoPtr->hwndEdit)
5525     {
5526         /* handle value will be lost after LISTVIEW_EndEditLabelT */
5527         HWND edit = infoPtr->hwndEdit;
5528 
5529         LISTVIEW_EndEditLabelT(infoPtr, TRUE, IsWindowUnicode(infoPtr->hwndEdit));
5530         SendMessageW(edit, WM_CLOSE, 0, 0);
5531     }
5532 
5533     return TRUE;
5534 }
5535 
5536 /***
5537  * DESCRIPTION:
5538  * Create a drag image list for the specified item.
5539  *
5540  * PARAMETER(S):
5541  * [I] infoPtr : valid pointer to the listview structure
5542  * [I] iItem   : index of item
5543  * [O] lppt    : Upper-left corner of the image
5544  *
5545  * RETURN:
5546  * Returns a handle to the image list if successful, NULL otherwise.
5547  */
5548 static HIMAGELIST LISTVIEW_CreateDragImage(LISTVIEW_INFO *infoPtr, INT iItem, LPPOINT lppt)
5549 {
5550     RECT rcItem;
5551     SIZE size;
5552     POINT pos;
5553     HDC hdc, hdcOrig;
5554     HBITMAP hbmp, hOldbmp;
5555     HFONT hOldFont;
5556     HIMAGELIST dragList = 0;
5557     TRACE("iItem=%d Count=%d\n", iItem, infoPtr->nItemCount);
5558 
5559     if (iItem < 0 || iItem >= infoPtr->nItemCount || !lppt)
5560         return 0;
5561 
5562     rcItem.left = LVIR_BOUNDS;
5563     if (!LISTVIEW_GetItemRect(infoPtr, iItem, &rcItem))
5564         return 0;
5565 
5566     lppt->x = rcItem.left;
5567     lppt->y = rcItem.top;
5568 
5569     size.cx = rcItem.right - rcItem.left;
5570     size.cy = rcItem.bottom - rcItem.top;
5571 
5572     hdcOrig = GetDC(infoPtr->hwndSelf);
5573     hdc = CreateCompatibleDC(hdcOrig);
5574     hbmp = CreateCompatibleBitmap(hdcOrig, size.cx, size.cy);
5575     hOldbmp = SelectObject(hdc, hbmp);
5576     hOldFont = SelectObject(hdc, infoPtr->hFont);
5577 
5578     SetRect(&rcItem, 0, 0, size.cx, size.cy);
5579     FillRect(hdc, &rcItem, infoPtr->hBkBrush);
5580 
5581     pos.x = pos.y = 0;
5582     if (LISTVIEW_DrawItem(infoPtr, hdc, iItem, NULL, pos, CDRF_DODEFAULT))
5583     {
5584         dragList = ImageList_Create(size.cx, size.cy, ILC_COLOR, 10, 10);
5585         SelectObject(hdc, hOldbmp);
5586         ImageList_Add(dragList, hbmp, 0);
5587     }
5588     else
5589         SelectObject(hdc, hOldbmp);
5590 
5591     SelectObject(hdc, hOldFont);
5592     DeleteObject(hbmp);
5593     DeleteDC(hdc);
5594     ReleaseDC(infoPtr->hwndSelf, hdcOrig);
5595 
5596     TRACE("ret=%p\n", dragList);
5597 
5598     return dragList;
5599 }
5600 
5601 
5602 /***
5603  * DESCRIPTION:
5604  * Removes all listview items and subitems.
5605  *
5606  * PARAMETER(S):
5607  * [I] infoPtr : valid pointer to the listview structure
5608  *
5609  * RETURN:
5610  *   SUCCESS : TRUE
5611  *   FAILURE : FALSE
5612  */
5613 static BOOL LISTVIEW_DeleteAllItems(LISTVIEW_INFO *infoPtr, BOOL destroy)
5614 {
5615     HDPA hdpaSubItems = NULL;
5616     BOOL suppress = FALSE;
5617     ITEMHDR *hdrItem;
5618     ITEM_INFO *lpItem;
5619     ITEM_ID *lpID;
5620     INT i, j;
5621 
5622     TRACE("()\n");
5623 
5624     /* we do it directly, to avoid notifications */
5625     ranges_clear(infoPtr->selectionRanges);
5626     infoPtr->nSelectionMark = -1;
5627     infoPtr->nFocusedItem = -1;
5628     SetRectEmpty(&infoPtr->rcFocus);
5629     /* But we are supposed to leave nHotItem as is! */
5630 
5631     /* send LVN_DELETEALLITEMS notification */
5632     if (!(infoPtr->dwStyle & LVS_OWNERDATA) || !destroy)
5633     {
5634         NMLISTVIEW nmlv;
5635 
5636         memset(&nmlv, 0, sizeof(NMLISTVIEW));
5637         nmlv.iItem = -1;
5638         suppress = notify_listview(infoPtr, LVN_DELETEALLITEMS, &nmlv);
5639     }
5640 
5641     for (i = infoPtr->nItemCount - 1; i >= 0; i--)
5642     {
5643 	if (!(infoPtr->dwStyle & LVS_OWNERDATA))
5644 	{
5645 	    /* send LVN_DELETEITEM notification, if not suppressed
5646 	       and if it is not a virtual listview */
5647 	    if (!suppress) notify_deleteitem(infoPtr, i);
5648 	    hdpaSubItems = DPA_GetPtr(infoPtr->hdpaItems, i);
5649 	    lpItem = DPA_GetPtr(hdpaSubItems, 0);
5650 	    /* free id struct */
5651 	    j = DPA_GetPtrIndex(infoPtr->hdpaItemIds, lpItem->id);
5652 	    lpID = DPA_GetPtr(infoPtr->hdpaItemIds, j);
5653 	    DPA_DeletePtr(infoPtr->hdpaItemIds, j);
5654 	    Free(lpID);
5655 	    /* both item and subitem start with ITEMHDR header */
5656 	    for (j = 0; j < DPA_GetPtrCount(hdpaSubItems); j++)
5657 	    {
5658 	        hdrItem = DPA_GetPtr(hdpaSubItems, j);
5659 		if (is_text(hdrItem->pszText)) Free(hdrItem->pszText);
5660 		Free(hdrItem);
5661 	    }
5662 	    DPA_Destroy(hdpaSubItems);
5663 	    DPA_DeletePtr(infoPtr->hdpaItems, i);
5664 	}
5665 	DPA_DeletePtr(infoPtr->hdpaPosX, i);
5666 	DPA_DeletePtr(infoPtr->hdpaPosY, i);
5667 	infoPtr->nItemCount --;
5668     }
5669 
5670     if (!destroy)
5671     {
5672         LISTVIEW_Arrange(infoPtr, LVA_DEFAULT);
5673         LISTVIEW_UpdateScroll(infoPtr);
5674     }
5675     LISTVIEW_InvalidateList(infoPtr);
5676 
5677     return TRUE;
5678 }
5679 
5680 /***
5681  * DESCRIPTION:
5682  * Scrolls, and updates the columns, when a column is changing width.
5683  *
5684  * PARAMETER(S):
5685  * [I] infoPtr : valid pointer to the listview structure
5686  * [I] nColumn : column to scroll
5687  * [I] dx : amount of scroll, in pixels
5688  *
5689  * RETURN:
5690  *   None.
5691  */
5692 static void LISTVIEW_ScrollColumns(LISTVIEW_INFO *infoPtr, INT nColumn, INT dx)
5693 {
5694     COLUMN_INFO *lpColumnInfo;
5695     RECT rcOld, rcCol;
5696     POINT ptOrigin;
5697     INT nCol;
5698     HDITEMW hdi;
5699 
5700     if (nColumn < 0 || DPA_GetPtrCount(infoPtr->hdpaColumns) < 1) return;
5701     lpColumnInfo = LISTVIEW_GetColumnInfo(infoPtr, min(nColumn, DPA_GetPtrCount(infoPtr->hdpaColumns) - 1));
5702     rcCol = lpColumnInfo->rcHeader;
5703     if (nColumn >= DPA_GetPtrCount(infoPtr->hdpaColumns))
5704 	rcCol.left = rcCol.right;
5705 
5706     /* adjust the other columns */
5707     hdi.mask = HDI_ORDER;
5708     if (SendMessageW(infoPtr->hwndHeader, HDM_GETITEMW, nColumn, (LPARAM)&hdi))
5709     {
5710 	INT nOrder = hdi.iOrder;
5711 	for (nCol = 0; nCol < DPA_GetPtrCount(infoPtr->hdpaColumns); nCol++)
5712 	{
5713 	    hdi.mask = HDI_ORDER;
5714 	    SendMessageW(infoPtr->hwndHeader, HDM_GETITEMW, nCol, (LPARAM)&hdi);
5715 	    if (hdi.iOrder >= nOrder) {
5716 		lpColumnInfo = LISTVIEW_GetColumnInfo(infoPtr, nCol);
5717 		lpColumnInfo->rcHeader.left  += dx;
5718 		lpColumnInfo->rcHeader.right += dx;
5719 	    }
5720 	}
5721     }
5722 
5723     /* do not update screen if not in report mode */
5724     if (!is_redrawing(infoPtr) || infoPtr->uView != LV_VIEW_DETAILS) return;
5725 
5726     /* Need to reset the item width when inserting a new column */
5727     infoPtr->nItemWidth += dx;
5728 
5729     LISTVIEW_UpdateScroll(infoPtr);
5730     LISTVIEW_GetOrigin(infoPtr, &ptOrigin);
5731 
5732     /* scroll to cover the deleted column, and invalidate for redraw */
5733     rcOld = infoPtr->rcList;
5734     rcOld.left = ptOrigin.x + rcCol.left + dx;
5735     ScrollWindowEx(infoPtr->hwndSelf, dx, 0, &rcOld, &rcOld, 0, 0, SW_ERASE | SW_INVALIDATE);
5736 }
5737 
5738 /***
5739  * DESCRIPTION:
5740  * Removes a column from the listview control.
5741  *
5742  * PARAMETER(S):
5743  * [I] infoPtr : valid pointer to the listview structure
5744  * [I] nColumn : column index
5745  *
5746  * RETURN:
5747  *   SUCCESS : TRUE
5748  *   FAILURE : FALSE
5749  */
5750 static BOOL LISTVIEW_DeleteColumn(LISTVIEW_INFO *infoPtr, INT nColumn)
5751 {
5752     RECT rcCol;
5753 
5754     TRACE("nColumn=%d\n", nColumn);
5755 
5756     if (nColumn < 0 || nColumn >= DPA_GetPtrCount(infoPtr->hdpaColumns))
5757         return FALSE;
5758 
5759     /* While the MSDN specifically says that column zero should not be deleted,
5760        what actually happens is that the column itself is deleted but no items or subitems
5761        are removed.
5762      */
5763 
5764     LISTVIEW_GetHeaderRect(infoPtr, nColumn, &rcCol);
5765 
5766     if (!SendMessageW(infoPtr->hwndHeader, HDM_DELETEITEM, nColumn, 0))
5767 	return FALSE;
5768 
5769     Free(DPA_GetPtr(infoPtr->hdpaColumns, nColumn));
5770     DPA_DeletePtr(infoPtr->hdpaColumns, nColumn);
5771 
5772     if (!(infoPtr->dwStyle & LVS_OWNERDATA) && nColumn)
5773     {
5774 	SUBITEM_INFO *lpSubItem, *lpDelItem;
5775 	HDPA hdpaSubItems;
5776 	INT nItem, nSubItem, i;
5777 
5778 	for (nItem = 0; nItem < infoPtr->nItemCount; nItem++)
5779 	{
5780             hdpaSubItems = DPA_GetPtr(infoPtr->hdpaItems, nItem);
5781 	    nSubItem = 0;
5782 	    lpDelItem = 0;
5783 	    for (i = 1; i < DPA_GetPtrCount(hdpaSubItems); i++)
5784 	    {
5785                 lpSubItem = DPA_GetPtr(hdpaSubItems, i);
5786 		if (lpSubItem->iSubItem == nColumn)
5787 		{
5788 		    nSubItem = i;
5789 		    lpDelItem = lpSubItem;
5790 		}
5791 		else if (lpSubItem->iSubItem > nColumn)
5792 		{
5793 		    lpSubItem->iSubItem--;
5794 		}
5795 	    }
5796 
5797 	    /* if we found our subitem, zap it */
5798 	    if (nSubItem > 0)
5799 	    {
5800 		/* free string */
5801 		if (is_text(lpDelItem->hdr.pszText))
5802 		    Free(lpDelItem->hdr.pszText);
5803 
5804 		/* free item */
5805 		Free(lpDelItem);
5806 
5807 		/* free dpa memory */
5808 		DPA_DeletePtr(hdpaSubItems, nSubItem);
5809     	    }
5810 	}
5811     }
5812 
5813     /* update the other column info */
5814     if(DPA_GetPtrCount(infoPtr->hdpaColumns) == 0)
5815         LISTVIEW_InvalidateList(infoPtr);
5816     else
5817         LISTVIEW_ScrollColumns(infoPtr, nColumn, -(rcCol.right - rcCol.left));
5818     LISTVIEW_UpdateItemSize(infoPtr);
5819 
5820     return TRUE;
5821 }
5822 
5823 /***
5824  * DESCRIPTION:
5825  * Invalidates the listview after an item's insertion or deletion.
5826  *
5827  * PARAMETER(S):
5828  * [I] infoPtr : valid pointer to the listview structure
5829  * [I] nItem : item index
5830  * [I] dir : -1 if deleting, 1 if inserting
5831  *
5832  * RETURN:
5833  *   None
5834  */
5835 static void LISTVIEW_ScrollOnInsert(LISTVIEW_INFO *infoPtr, INT nItem, INT dir)
5836 {
5837     INT nPerCol, nItemCol, nItemRow;
5838     RECT rcScroll;
5839     POINT Origin;
5840 
5841     /* if we don't refresh, what's the point of scrolling? */
5842     if (!is_redrawing(infoPtr)) return;
5843 
5844     assert (abs(dir) == 1);
5845 
5846     /* arrange icons if autoarrange is on */
5847     if (is_autoarrange(infoPtr))
5848     {
5849 	BOOL arrange = TRUE;
5850 	if (dir < 0 && nItem >= infoPtr->nItemCount) arrange = FALSE;
5851 	if (dir > 0 && nItem == infoPtr->nItemCount - 1) arrange = FALSE;
5852 	if (arrange) LISTVIEW_Arrange(infoPtr, LVA_DEFAULT);
5853     }
5854 
5855     /* scrollbars need updating */
5856     LISTVIEW_UpdateScroll(infoPtr);
5857 
5858     /* figure out the item's position */
5859     if (infoPtr->uView == LV_VIEW_DETAILS)
5860 	nPerCol = infoPtr->nItemCount + 1;
5861     else if (infoPtr->uView == LV_VIEW_LIST)
5862 	nPerCol = LISTVIEW_GetCountPerColumn(infoPtr);
5863     else /* LV_VIEW_ICON, or LV_VIEW_SMALLICON */
5864 	return;
5865 
5866     nItemCol = nItem / nPerCol;
5867     nItemRow = nItem % nPerCol;
5868     LISTVIEW_GetOrigin(infoPtr, &Origin);
5869 
5870     /* move the items below up a slot */
5871     rcScroll.left = nItemCol * infoPtr->nItemWidth;
5872     rcScroll.top = nItemRow * infoPtr->nItemHeight;
5873     rcScroll.right = rcScroll.left + infoPtr->nItemWidth;
5874     rcScroll.bottom = nPerCol * infoPtr->nItemHeight;
5875     OffsetRect(&rcScroll, Origin.x, Origin.y);
5876     TRACE("rcScroll=%s, dx=%d\n", wine_dbgstr_rect(&rcScroll), dir * infoPtr->nItemHeight);
5877     if (IntersectRect(&rcScroll, &rcScroll, &infoPtr->rcList))
5878     {
5879 	TRACE("Invalidating rcScroll=%s, rcList=%s\n", wine_dbgstr_rect(&rcScroll), wine_dbgstr_rect(&infoPtr->rcList));
5880 	InvalidateRect(infoPtr->hwndSelf, &rcScroll, TRUE);
5881     }
5882 
5883     /* report has only that column, so we're done */
5884     if (infoPtr->uView == LV_VIEW_DETAILS) return;
5885 
5886     /* now for LISTs, we have to deal with the columns to the right */
5887     SetRect(&rcScroll, (nItemCol + 1) * infoPtr->nItemWidth, 0,
5888             (infoPtr->nItemCount / nPerCol + 1) * infoPtr->nItemWidth,
5889             nPerCol * infoPtr->nItemHeight);
5890     OffsetRect(&rcScroll, Origin.x, Origin.y);
5891     if (IntersectRect(&rcScroll, &rcScroll, &infoPtr->rcList))
5892 	InvalidateRect(infoPtr->hwndSelf, &rcScroll, TRUE);
5893 }
5894 
5895 /***
5896  * DESCRIPTION:
5897  * Removes an item from the listview control.
5898  *
5899  * PARAMETER(S):
5900  * [I] infoPtr : valid pointer to the listview structure
5901  * [I] nItem : item index
5902  *
5903  * RETURN:
5904  *   SUCCESS : TRUE
5905  *   FAILURE : FALSE
5906  */
5907 static BOOL LISTVIEW_DeleteItem(LISTVIEW_INFO *infoPtr, INT nItem)
5908 {
5909     LVITEMW item;
5910     const BOOL is_icon = (infoPtr->uView == LV_VIEW_SMALLICON || infoPtr->uView == LV_VIEW_ICON);
5911     INT focus = infoPtr->nFocusedItem;
5912 
5913     TRACE("(nItem=%d)\n", nItem);
5914 
5915     if (nItem < 0 || nItem >= infoPtr->nItemCount) return FALSE;
5916 
5917     /* remove selection, and focus */
5918     item.state = 0;
5919     item.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
5920     LISTVIEW_SetItemState(infoPtr, nItem, &item);
5921 
5922     /* send LVN_DELETEITEM notification. */
5923     if (!notify_deleteitem(infoPtr, nItem)) return FALSE;
5924 
5925     /* we need to do this here, because we'll be deleting stuff */
5926     if (is_icon)
5927 	LISTVIEW_InvalidateItem(infoPtr, nItem);
5928 
5929     if (!(infoPtr->dwStyle & LVS_OWNERDATA))
5930     {
5931         HDPA hdpaSubItems;
5932 	ITEMHDR *hdrItem;
5933 	ITEM_INFO *lpItem;
5934 	ITEM_ID *lpID;
5935 	INT i;
5936 
5937 	hdpaSubItems = DPA_DeletePtr(infoPtr->hdpaItems, nItem);
5938 	lpItem = DPA_GetPtr(hdpaSubItems, 0);
5939 
5940 	/* free id struct */
5941 	i = DPA_GetPtrIndex(infoPtr->hdpaItemIds, lpItem->id);
5942 	lpID = DPA_GetPtr(infoPtr->hdpaItemIds, i);
5943 	DPA_DeletePtr(infoPtr->hdpaItemIds, i);
5944 	Free(lpID);
5945 	for (i = 0; i < DPA_GetPtrCount(hdpaSubItems); i++)
5946     	{
5947             hdrItem = DPA_GetPtr(hdpaSubItems, i);
5948 	    if (is_text(hdrItem->pszText)) Free(hdrItem->pszText);
5949             Free(hdrItem);
5950         }
5951         DPA_Destroy(hdpaSubItems);
5952     }
5953 
5954     if (is_icon)
5955     {
5956 	DPA_DeletePtr(infoPtr->hdpaPosX, nItem);
5957 	DPA_DeletePtr(infoPtr->hdpaPosY, nItem);
5958     }
5959 
5960     infoPtr->nItemCount--;
5961     LISTVIEW_ShiftIndices(infoPtr, nItem, -1);
5962     LISTVIEW_ShiftFocus(infoPtr, focus, nItem, -1);
5963 
5964     /* now is the invalidation fun */
5965     if (!is_icon)
5966         LISTVIEW_ScrollOnInsert(infoPtr, nItem, -1);
5967     return TRUE;
5968 }
5969 
5970 
5971 /***
5972  * DESCRIPTION:
5973  * Callback implementation for editlabel control
5974  *
5975  * PARAMETER(S):
5976  * [I] infoPtr : valid pointer to the listview structure
5977  * [I] storeText : store edit box text as item text
5978  * [I] isW : TRUE if psxText is Unicode, FALSE if it's ANSI
5979  *
5980  * RETURN:
5981  *   SUCCESS : TRUE
5982  *   FAILURE : FALSE
5983  */
5984 static BOOL LISTVIEW_EndEditLabelT(LISTVIEW_INFO *infoPtr, BOOL storeText, BOOL isW)
5985 {
5986     HWND hwndSelf = infoPtr->hwndSelf;
5987     WCHAR szDispText[DISP_TEXT_SIZE] = { 0 };
5988     NMLVDISPINFOW dispInfo;
5989     INT editedItem = infoPtr->nEditLabelItem;
5990     BOOL same;
5991     WCHAR *pszText = NULL;
5992     BOOL res;
5993 
5994     if (storeText)
5995     {
5996         DWORD len = isW ? GetWindowTextLengthW(infoPtr->hwndEdit) : GetWindowTextLengthA(infoPtr->hwndEdit);
5997 
5998         if (len++)
5999         {
6000             if (!(pszText = Alloc(len * (isW ? sizeof(WCHAR) : sizeof(CHAR)))))
6001                 return FALSE;
6002 
6003             if (isW)
6004                 GetWindowTextW(infoPtr->hwndEdit, pszText, len);
6005             else
6006                 GetWindowTextA(infoPtr->hwndEdit, (CHAR*)pszText, len);
6007         }
6008     }
6009 
6010     TRACE("(pszText=%s, isW=%d)\n", debugtext_t(pszText, isW), isW);
6011 
6012     ZeroMemory(&dispInfo, sizeof(dispInfo));
6013     dispInfo.item.mask = LVIF_PARAM | LVIF_STATE | LVIF_TEXT;
6014     dispInfo.item.iItem = editedItem;
6015     dispInfo.item.iSubItem = 0;
6016     dispInfo.item.stateMask = ~0;
6017     dispInfo.item.pszText = szDispText;
6018     dispInfo.item.cchTextMax = DISP_TEXT_SIZE;
6019     if (!LISTVIEW_GetItemT(infoPtr, &dispInfo.item, isW))
6020     {
6021        res = FALSE;
6022        goto cleanup;
6023     }
6024 
6025     if (isW)
6026         same = (lstrcmpW(dispInfo.item.pszText, pszText) == 0);
6027     else
6028     {
6029         LPWSTR tmp = textdupTtoW(pszText, FALSE);
6030         same = (lstrcmpW(dispInfo.item.pszText, tmp) == 0);
6031         textfreeT(tmp, FALSE);
6032     }
6033 
6034     /* add the text from the edit in */
6035     dispInfo.item.mask |= LVIF_TEXT;
6036     dispInfo.item.pszText = same ? NULL : pszText;
6037     dispInfo.item.cchTextMax = textlenT(dispInfo.item.pszText, isW);
6038 
6039     infoPtr->notify_mask &= ~NOTIFY_MASK_END_LABEL_EDIT;
6040 
6041     /* Do we need to update the Item Text */
6042     res = notify_dispinfoT(infoPtr, LVN_ENDLABELEDITW, &dispInfo, isW);
6043 
6044     infoPtr->notify_mask |= NOTIFY_MASK_END_LABEL_EDIT;
6045 
6046     infoPtr->nEditLabelItem = -1;
6047     infoPtr->hwndEdit = 0;
6048 
6049     if (!res) goto cleanup;
6050 
6051     if (!IsWindow(hwndSelf))
6052     {
6053 	res = FALSE;
6054 	goto cleanup;
6055     }
6056     if (!pszText) return TRUE;
6057     if (same)
6058     {
6059         res = TRUE;
6060         goto cleanup;
6061     }
6062 
6063     if (!(infoPtr->dwStyle & LVS_OWNERDATA))
6064     {
6065         HDPA hdpaSubItems = DPA_GetPtr(infoPtr->hdpaItems, editedItem);
6066         ITEM_INFO* lpItem = DPA_GetPtr(hdpaSubItems, 0);
6067         if (lpItem && lpItem->hdr.pszText == LPSTR_TEXTCALLBACKW)
6068         {
6069             LISTVIEW_InvalidateItem(infoPtr, editedItem);
6070             res = TRUE;
6071             goto cleanup;
6072         }
6073     }
6074 
6075     ZeroMemory(&dispInfo, sizeof(dispInfo));
6076     dispInfo.item.mask = LVIF_TEXT;
6077     dispInfo.item.iItem = editedItem;
6078     dispInfo.item.iSubItem = 0;
6079     dispInfo.item.pszText = pszText;
6080     dispInfo.item.cchTextMax = textlenT(pszText, isW);
6081     res = LISTVIEW_SetItemT(infoPtr, &dispInfo.item, isW);
6082 
6083 cleanup:
6084     Free(pszText);
6085 
6086     return res;
6087 }
6088 
6089 /***
6090  * DESCRIPTION:
6091  * Subclassed edit control windproc function
6092  *
6093  * PARAMETER(S):
6094  * [I] hwnd : the edit window handle
6095  * [I] uMsg : the message that is to be processed
6096  * [I] wParam : first message parameter
6097  * [I] lParam : second message parameter
6098  * [I] isW : TRUE if input is Unicode
6099  *
6100  * RETURN:
6101  *   Zero.
6102  */
6103 static LRESULT EditLblWndProcT(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL isW)
6104 {
6105     LISTVIEW_INFO *infoPtr = (LISTVIEW_INFO *)GetWindowLongPtrW(GetParent(hwnd), 0);
6106     BOOL save = TRUE;
6107 
6108     TRACE("(hwnd=%p, uMsg=%x, wParam=%lx, lParam=%lx, isW=%d)\n",
6109 	  hwnd, uMsg, wParam, lParam, isW);
6110 
6111     switch (uMsg)
6112     {
6113 	case WM_GETDLGCODE:
6114 	  return DLGC_WANTARROWS | DLGC_WANTALLKEYS;
6115 
6116 	case WM_DESTROY:
6117 	{
6118 	    WNDPROC editProc = infoPtr->EditWndProc;
6119 	    infoPtr->EditWndProc = 0;
6120 	    SetWindowLongPtrW(hwnd, GWLP_WNDPROC, (DWORD_PTR)editProc);
6121 	    return CallWindowProcT(editProc, hwnd, uMsg, wParam, lParam, isW);
6122 	}
6123 
6124 	case WM_KEYDOWN:
6125 	    if (VK_ESCAPE == (INT)wParam)
6126 	    {
6127 		save = FALSE;
6128                 break;
6129 	    }
6130 	    else if (VK_RETURN == (INT)wParam)
6131 		break;
6132 
6133 	default:
6134 	    return CallWindowProcT(infoPtr->EditWndProc, hwnd, uMsg, wParam, lParam, isW);
6135     }
6136 
6137     /* kill the edit */
6138     if (infoPtr->hwndEdit)
6139 	LISTVIEW_EndEditLabelT(infoPtr, save, isW);
6140 
6141     SendMessageW(hwnd, WM_CLOSE, 0, 0);
6142     return 0;
6143 }
6144 
6145 /***
6146  * DESCRIPTION:
6147  * Subclassed edit control Unicode windproc function
6148  *
6149  * PARAMETER(S):
6150  * [I] hwnd : the edit window handle
6151  * [I] uMsg : the message that is to be processed
6152  * [I] wParam : first message parameter
6153  * [I] lParam : second message parameter
6154  *
6155  * RETURN:
6156  */
6157 static LRESULT CALLBACK EditLblWndProcW(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
6158 {
6159     return EditLblWndProcT(hwnd, uMsg, wParam, lParam, TRUE);
6160 }
6161 
6162 /***
6163  * DESCRIPTION:
6164  * Subclassed edit control ANSI windproc function
6165  *
6166  * PARAMETER(S):
6167  * [I] hwnd : the edit window handle
6168  * [I] uMsg : the message that is to be processed
6169  * [I] wParam : first message parameter
6170  * [I] lParam : second message parameter
6171  *
6172  * RETURN:
6173  */
6174 static LRESULT CALLBACK EditLblWndProcA(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
6175 {
6176     return EditLblWndProcT(hwnd, uMsg, wParam, lParam, FALSE);
6177 }
6178 
6179 /***
6180  * DESCRIPTION:
6181  * Creates a subclassed edit control
6182  *
6183  * PARAMETER(S):
6184  * [I] infoPtr : valid pointer to the listview structure
6185  * [I] text : initial text for the edit
6186  * [I] style : the window style
6187  * [I] isW : TRUE if input is Unicode
6188  *
6189  * RETURN:
6190  */
6191 static HWND CreateEditLabelT(LISTVIEW_INFO *infoPtr, LPCWSTR text, BOOL isW)
6192 {
6193     static const DWORD style = WS_CHILDWINDOW|WS_CLIPSIBLINGS|ES_LEFT|ES_AUTOHSCROLL|WS_BORDER|WS_VISIBLE;
6194     HINSTANCE hinst = (HINSTANCE)GetWindowLongPtrW(infoPtr->hwndSelf, GWLP_HINSTANCE);
6195     HWND hedit;
6196 
6197     TRACE("(%p, text=%s, isW=%d)\n", infoPtr, debugtext_t(text, isW), isW);
6198 
6199     /* window will be resized and positioned after LVN_BEGINLABELEDIT */
6200     if (isW)
6201 	hedit = CreateWindowW(WC_EDITW, text, style, 0, 0, 0, 0, infoPtr->hwndSelf, 0, hinst, 0);
6202     else
6203 	hedit = CreateWindowA(WC_EDITA, (LPCSTR)text, style, 0, 0, 0, 0, infoPtr->hwndSelf, 0, hinst, 0);
6204 
6205     if (!hedit) return 0;
6206 
6207     infoPtr->EditWndProc = (WNDPROC)
6208 	(isW ? SetWindowLongPtrW(hedit, GWLP_WNDPROC, (DWORD_PTR)EditLblWndProcW) :
6209                SetWindowLongPtrA(hedit, GWLP_WNDPROC, (DWORD_PTR)EditLblWndProcA) );
6210 
6211     SendMessageW(hedit, WM_SETFONT, (WPARAM)infoPtr->hFont, FALSE);
6212     SendMessageW(hedit, EM_SETLIMITTEXT, DISP_TEXT_SIZE-1, 0);
6213 
6214     return hedit;
6215 }
6216 
6217 /***
6218  * DESCRIPTION:
6219  * Begin in place editing of specified list view item
6220  *
6221  * PARAMETER(S):
6222  * [I] infoPtr : valid pointer to the listview structure
6223  * [I] nItem : item index
6224  * [I] isW : TRUE if it's a Unicode req, FALSE if ASCII
6225  *
6226  * RETURN:
6227  *   SUCCESS : TRUE
6228  *   FAILURE : FALSE
6229  */
6230 static HWND LISTVIEW_EditLabelT(LISTVIEW_INFO *infoPtr, INT nItem, BOOL isW)
6231 {
6232     WCHAR disptextW[DISP_TEXT_SIZE] = { 0 };
6233     HWND hwndSelf = infoPtr->hwndSelf;
6234     NMLVDISPINFOW dispInfo;
6235     HFONT hOldFont = NULL;
6236     TEXTMETRICW tm;
6237     RECT rect;
6238     SIZE sz;
6239     HDC hdc;
6240 
6241     TRACE("(nItem=%d, isW=%d)\n", nItem, isW);
6242 
6243     if (~infoPtr->dwStyle & LVS_EDITLABELS) return 0;
6244 
6245     /* remove existing edit box */
6246     if (infoPtr->hwndEdit)
6247     {
6248         SetFocus(infoPtr->hwndSelf);
6249         infoPtr->hwndEdit = 0;
6250     }
6251 
6252     if (nItem < 0 || nItem >= infoPtr->nItemCount) return 0;
6253 
6254     infoPtr->nEditLabelItem = nItem;
6255 
6256     LISTVIEW_SetSelection(infoPtr, nItem);
6257     LISTVIEW_SetItemFocus(infoPtr, nItem);
6258     LISTVIEW_InvalidateItem(infoPtr, nItem);
6259 
6260     rect.left = LVIR_LABEL;
6261     if (!LISTVIEW_GetItemRect(infoPtr, nItem, &rect)) return 0;
6262 
6263     ZeroMemory(&dispInfo, sizeof(dispInfo));
6264     dispInfo.item.mask = LVIF_PARAM | LVIF_STATE | LVIF_TEXT;
6265     dispInfo.item.iItem = nItem;
6266     dispInfo.item.iSubItem = 0;
6267     dispInfo.item.stateMask = ~0;
6268     dispInfo.item.pszText = disptextW;
6269     dispInfo.item.cchTextMax = DISP_TEXT_SIZE;
6270     if (!LISTVIEW_GetItemT(infoPtr, &dispInfo.item, isW)) return 0;
6271 
6272     infoPtr->hwndEdit = CreateEditLabelT(infoPtr, dispInfo.item.pszText, isW);
6273     if (!infoPtr->hwndEdit) return 0;
6274 
6275     if (notify_dispinfoT(infoPtr, LVN_BEGINLABELEDITW, &dispInfo, isW))
6276     {
6277 	if (!IsWindow(hwndSelf))
6278 	    return 0;
6279 	SendMessageW(infoPtr->hwndEdit, WM_CLOSE, 0, 0);
6280 	infoPtr->hwndEdit = 0;
6281 	return 0;
6282     }
6283 
6284     TRACE("disp text=%s\n", debugtext_t(dispInfo.item.pszText, isW));
6285 
6286     /* position and display edit box */
6287     hdc = GetDC(infoPtr->hwndSelf);
6288 
6289     /* select the font to get appropriate metric dimensions */
6290     if (infoPtr->hFont)
6291         hOldFont = SelectObject(hdc, infoPtr->hFont);
6292 
6293     /* use real edit box content, it could be altered during LVN_BEGINLABELEDIT notification */
6294     GetWindowTextW(infoPtr->hwndEdit, disptextW, DISP_TEXT_SIZE);
6295     TRACE("edit box text=%s\n", debugstr_w(disptextW));
6296 
6297     /* get string length in pixels */
6298     GetTextExtentPoint32W(hdc, disptextW, lstrlenW(disptextW), &sz);
6299 
6300     /* add extra spacing for the next character */
6301     GetTextMetricsW(hdc, &tm);
6302     sz.cx += tm.tmMaxCharWidth * 2;
6303 
6304     if (infoPtr->hFont)
6305         SelectObject(hdc, hOldFont);
6306 
6307     ReleaseDC(infoPtr->hwndSelf, hdc);
6308 
6309     sz.cy = rect.bottom - rect.top + 2;
6310     rect.left -= 2;
6311     rect.top  -= 1;
6312     TRACE("moving edit=(%d,%d)-(%d,%d)\n", rect.left, rect.top, sz.cx, sz.cy);
6313     MoveWindow(infoPtr->hwndEdit, rect.left, rect.top, sz.cx, sz.cy, FALSE);
6314     ShowWindow(infoPtr->hwndEdit, SW_NORMAL);
6315     SetFocus(infoPtr->hwndEdit);
6316     SendMessageW(infoPtr->hwndEdit, EM_SETSEL, 0, -1);
6317     return infoPtr->hwndEdit;
6318 }
6319 
6320 
6321 /***
6322  * DESCRIPTION:
6323  * Ensures the specified item is visible, scrolling into view if necessary.
6324  *
6325  * PARAMETER(S):
6326  * [I] infoPtr : valid pointer to the listview structure
6327  * [I] nItem : item index
6328  * [I] bPartial : partially or entirely visible
6329  *
6330  * RETURN:
6331  *   SUCCESS : TRUE
6332  *   FAILURE : FALSE
6333  */
6334 static BOOL LISTVIEW_EnsureVisible(LISTVIEW_INFO *infoPtr, INT nItem, BOOL bPartial)
6335 {
6336     INT nScrollPosHeight = 0;
6337     INT nScrollPosWidth = 0;
6338     INT nHorzAdjust = 0;
6339     INT nVertAdjust = 0;
6340     INT nHorzDiff = 0;
6341     INT nVertDiff = 0;
6342     RECT rcItem, rcTemp;
6343 
6344     rcItem.left = LVIR_BOUNDS;
6345     if (!LISTVIEW_GetItemRect(infoPtr, nItem, &rcItem)) return FALSE;
6346 
6347     if (bPartial && IntersectRect(&rcTemp, &infoPtr->rcList, &rcItem)) return TRUE;
6348 
6349     if (rcItem.left < infoPtr->rcList.left || rcItem.right > infoPtr->rcList.right)
6350     {
6351         /* scroll left/right, but in LV_VIEW_DETAILS mode */
6352         if (infoPtr->uView == LV_VIEW_LIST)
6353             nScrollPosWidth = infoPtr->nItemWidth;
6354         else if ((infoPtr->uView == LV_VIEW_SMALLICON) || (infoPtr->uView == LV_VIEW_ICON))
6355             nScrollPosWidth = 1;
6356 
6357 	if (rcItem.left < infoPtr->rcList.left)
6358 	{
6359 	    nHorzAdjust = -1;
6360 	    if (infoPtr->uView != LV_VIEW_DETAILS) nHorzDiff = rcItem.left - infoPtr->rcList.left;
6361 	}
6362 	else
6363 	{
6364 	    nHorzAdjust = 1;
6365 	    if (infoPtr->uView != LV_VIEW_DETAILS) nHorzDiff = rcItem.right - infoPtr->rcList.right;
6366 	}
6367     }
6368 
6369     if (rcItem.top < infoPtr->rcList.top || rcItem.bottom > infoPtr->rcList.bottom)
6370     {
6371 	/* scroll up/down, but not in LVS_LIST mode */
6372         if (infoPtr->uView == LV_VIEW_DETAILS)
6373             nScrollPosHeight = infoPtr->nItemHeight;
6374         else if ((infoPtr->uView == LV_VIEW_ICON) || (infoPtr->uView == LV_VIEW_SMALLICON))
6375             nScrollPosHeight = 1;
6376 
6377 	if (rcItem.top < infoPtr->rcList.top)
6378 	{
6379 	    nVertAdjust = -1;
6380 	    if (infoPtr->uView != LV_VIEW_LIST) nVertDiff = rcItem.top - infoPtr->rcList.top;
6381 	}
6382 	else
6383 	{
6384 	    nVertAdjust = 1;
6385 	    if (infoPtr->uView != LV_VIEW_LIST) nVertDiff = rcItem.bottom - infoPtr->rcList.bottom;
6386 	}
6387     }
6388 
6389     if (!nScrollPosWidth && !nScrollPosHeight) return TRUE;
6390 
6391     if (nScrollPosWidth)
6392     {
6393 	INT diff = nHorzDiff / nScrollPosWidth;
6394 	if (nHorzDiff % nScrollPosWidth) diff += nHorzAdjust;
6395 	LISTVIEW_HScroll(infoPtr, SB_INTERNAL, diff);
6396     }
6397 
6398     if (nScrollPosHeight)
6399     {
6400 	INT diff = nVertDiff / nScrollPosHeight;
6401 	if (nVertDiff % nScrollPosHeight) diff += nVertAdjust;
6402 	LISTVIEW_VScroll(infoPtr, SB_INTERNAL, diff);
6403     }
6404 
6405     return TRUE;
6406 }
6407 
6408 /***
6409  * DESCRIPTION:
6410  * Searches for an item with specific characteristics.
6411  *
6412  * PARAMETER(S):
6413  * [I] hwnd : window handle
6414  * [I] nStart : base item index
6415  * [I] lpFindInfo : item information to look for
6416  *
6417  * RETURN:
6418  *   SUCCESS : index of item
6419  *   FAILURE : -1
6420  */
6421 static INT LISTVIEW_FindItemW(const LISTVIEW_INFO *infoPtr, INT nStart,
6422                               const LVFINDINFOW *lpFindInfo)
6423 {
6424     WCHAR szDispText[DISP_TEXT_SIZE] = { '\0' };
6425     BOOL bWrap = FALSE, bNearest = FALSE;
6426     INT nItem = nStart + 1, nLast = infoPtr->nItemCount, nNearestItem = -1;
6427     ULONG xdist, ydist, dist, mindist = 0x7fffffff;
6428     POINT Position, Destination;
6429     LVITEMW lvItem;
6430 
6431     /* Search in virtual listviews should be done by application, not by
6432        listview control, so we just send LVN_ODFINDITEMW and return the result */
6433     if (infoPtr->dwStyle & LVS_OWNERDATA)
6434     {
6435         NMLVFINDITEMW nmlv;
6436 
6437         nmlv.iStart = nStart;
6438         nmlv.lvfi = *lpFindInfo;
6439         return notify_hdr(infoPtr, LVN_ODFINDITEMW, (LPNMHDR)&nmlv.hdr);
6440     }
6441 
6442     if (!lpFindInfo || nItem < 0) return -1;
6443 
6444     lvItem.mask = 0;
6445     if (lpFindInfo->flags & (LVFI_STRING | LVFI_PARTIAL | LVFI_SUBSTRING))
6446     {
6447         lvItem.mask |= LVIF_TEXT;
6448         lvItem.pszText = szDispText;
6449         lvItem.cchTextMax = DISP_TEXT_SIZE;
6450     }
6451 
6452     if (lpFindInfo->flags & LVFI_WRAP)
6453         bWrap = TRUE;
6454 
6455     if ((lpFindInfo->flags & LVFI_NEARESTXY) &&
6456 	(infoPtr->uView == LV_VIEW_ICON || infoPtr->uView == LV_VIEW_SMALLICON))
6457     {
6458 	POINT Origin;
6459 	RECT rcArea;
6460 
6461         LISTVIEW_GetOrigin(infoPtr, &Origin);
6462 	Destination.x = lpFindInfo->pt.x - Origin.x;
6463 	Destination.y = lpFindInfo->pt.y - Origin.y;
6464 	switch(lpFindInfo->vkDirection)
6465 	{
6466 	case VK_DOWN:  Destination.y += infoPtr->nItemHeight; break;
6467 	case VK_UP:    Destination.y -= infoPtr->nItemHeight; break;
6468 	case VK_RIGHT: Destination.x += infoPtr->nItemWidth; break;
6469 	case VK_LEFT:  Destination.x -= infoPtr->nItemWidth; break;
6470 	case VK_HOME:  Destination.x = Destination.y = 0; break;
6471 	case VK_NEXT:  Destination.y += infoPtr->rcList.bottom - infoPtr->rcList.top; break;
6472 	case VK_PRIOR: Destination.y -= infoPtr->rcList.bottom - infoPtr->rcList.top; break;
6473 	case VK_END:
6474 	    LISTVIEW_GetAreaRect(infoPtr, &rcArea);
6475 	    Destination.x = rcArea.right;
6476 	    Destination.y = rcArea.bottom;
6477 	    break;
6478 	default: ERR("Unknown vkDirection=%d\n", lpFindInfo->vkDirection);
6479 	}
6480 	bNearest = TRUE;
6481     }
6482     else Destination.x = Destination.y = 0;
6483 
6484     /* if LVFI_PARAM is specified, all other flags are ignored */
6485     if (lpFindInfo->flags & LVFI_PARAM)
6486     {
6487         lvItem.mask |= LVIF_PARAM;
6488 	bNearest = FALSE;
6489 	lvItem.mask &= ~LVIF_TEXT;
6490     }
6491 
6492     nItem = bNearest ? -1 : nStart + 1;
6493 
6494 again:
6495     for (; nItem < nLast; nItem++)
6496     {
6497         lvItem.iItem = nItem;
6498         lvItem.iSubItem = 0;
6499         lvItem.pszText = szDispText;
6500         if (!LISTVIEW_GetItemW(infoPtr, &lvItem)) continue;
6501 
6502 	if (lvItem.mask & LVIF_PARAM)
6503         {
6504             if (lpFindInfo->lParam == lvItem.lParam)
6505                 return nItem;
6506             else
6507                 continue;
6508         }
6509 
6510         if (lvItem.mask & LVIF_TEXT)
6511 	{
6512             if (lpFindInfo->flags & (LVFI_PARTIAL | LVFI_SUBSTRING))
6513             {
6514 		WCHAR *p = wcsstr(lvItem.pszText, lpFindInfo->psz);
6515 		if (!p || p != lvItem.pszText) continue;
6516             }
6517             else
6518             {
6519             	if (lstrcmpW(lvItem.pszText, lpFindInfo->psz) != 0) continue;
6520             }
6521 	}
6522 
6523         if (!bNearest) return nItem;
6524 
6525 	/* This is very inefficient. To do a good job here,
6526 	 * we need a sorted array of (x,y) item positions */
6527 	LISTVIEW_GetItemOrigin(infoPtr, nItem, &Position);
6528 
6529 	/* compute the distance^2 to the destination */
6530 	xdist = Destination.x - Position.x;
6531 	ydist = Destination.y - Position.y;
6532 	dist = xdist * xdist + ydist * ydist;
6533 
6534 	/* remember the distance, and item if it's closer */
6535 	if (dist < mindist)
6536 	{
6537 	    mindist = dist;
6538 	    nNearestItem = nItem;
6539 	}
6540     }
6541 
6542     if (bWrap)
6543     {
6544         nItem = 0;
6545         nLast = min(nStart + 1, infoPtr->nItemCount);
6546         bWrap = FALSE;
6547 	goto again;
6548     }
6549 
6550     return nNearestItem;
6551 }
6552 
6553 /***
6554  * DESCRIPTION:
6555  * Searches for an item with specific characteristics.
6556  *
6557  * PARAMETER(S):
6558  * [I] hwnd : window handle
6559  * [I] nStart : base item index
6560  * [I] lpFindInfo : item information to look for
6561  *
6562  * RETURN:
6563  *   SUCCESS : index of item
6564  *   FAILURE : -1
6565  */
6566 static INT LISTVIEW_FindItemA(const LISTVIEW_INFO *infoPtr, INT nStart,
6567                               const LVFINDINFOA *lpFindInfo)
6568 {
6569     LVFINDINFOW fiw;
6570     INT res;
6571     LPWSTR strW = NULL;
6572 
6573     memcpy(&fiw, lpFindInfo, sizeof(fiw));
6574     if (lpFindInfo->flags & (LVFI_STRING | LVFI_PARTIAL | LVFI_SUBSTRING))
6575         fiw.psz = strW = textdupTtoW((LPCWSTR)lpFindInfo->psz, FALSE);
6576     res = LISTVIEW_FindItemW(infoPtr, nStart, &fiw);
6577     textfreeT(strW, FALSE);
6578     return res;
6579 }
6580 
6581 /***
6582  * DESCRIPTION:
6583  * Retrieves column attributes.
6584  *
6585  * PARAMETER(S):
6586  * [I] infoPtr : valid pointer to the listview structure
6587  * [I] nColumn :  column index
6588  * [IO] lpColumn : column information
6589  * [I] isW : if TRUE, then lpColumn is a LPLVCOLUMNW
6590  *           otherwise it is in fact a LPLVCOLUMNA
6591  *
6592  * RETURN:
6593  *   SUCCESS : TRUE
6594  *   FAILURE : FALSE
6595  */
6596 static BOOL LISTVIEW_GetColumnT(const LISTVIEW_INFO *infoPtr, INT nColumn, LPLVCOLUMNW lpColumn, BOOL isW)
6597 {
6598     COLUMN_INFO *lpColumnInfo;
6599     HDITEMW hdi;
6600 
6601     if (!lpColumn || nColumn < 0 || nColumn >= DPA_GetPtrCount(infoPtr->hdpaColumns)) return FALSE;
6602     lpColumnInfo = LISTVIEW_GetColumnInfo(infoPtr, nColumn);
6603 
6604     /* initialize memory */
6605     ZeroMemory(&hdi, sizeof(hdi));
6606 
6607     if (lpColumn->mask & LVCF_TEXT)
6608     {
6609         hdi.mask |= HDI_TEXT;
6610         hdi.pszText = lpColumn->pszText;
6611         hdi.cchTextMax = lpColumn->cchTextMax;
6612     }
6613 
6614     if (lpColumn->mask & LVCF_IMAGE)
6615         hdi.mask |= HDI_IMAGE;
6616 
6617     if (lpColumn->mask & LVCF_ORDER)
6618         hdi.mask |= HDI_ORDER;
6619 
6620     if (lpColumn->mask & LVCF_SUBITEM)
6621         hdi.mask |= HDI_LPARAM;
6622 
6623     if (!SendMessageW(infoPtr->hwndHeader, isW ? HDM_GETITEMW : HDM_GETITEMA, nColumn, (LPARAM)&hdi)) return FALSE;
6624 
6625     if (lpColumn->mask & LVCF_FMT)
6626 	lpColumn->fmt = lpColumnInfo->fmt;
6627 
6628     if (lpColumn->mask & LVCF_WIDTH)
6629         lpColumn->cx = lpColumnInfo->rcHeader.right - lpColumnInfo->rcHeader.left;
6630 
6631     if (lpColumn->mask & LVCF_IMAGE)
6632 	lpColumn->iImage = hdi.iImage;
6633 
6634     if (lpColumn->mask & LVCF_ORDER)
6635 	lpColumn->iOrder = hdi.iOrder;
6636 
6637     if (lpColumn->mask & LVCF_SUBITEM)
6638 	lpColumn->iSubItem = hdi.lParam;
6639 
6640     if (lpColumn->mask & LVCF_MINWIDTH)
6641 	lpColumn->cxMin = lpColumnInfo->cxMin;
6642 
6643     return TRUE;
6644 }
6645 
6646 static inline BOOL LISTVIEW_GetColumnOrderArray(const LISTVIEW_INFO *infoPtr, INT iCount, LPINT lpiArray)
6647 {
6648     if (!infoPtr->hwndHeader) return FALSE;
6649     return SendMessageW(infoPtr->hwndHeader, HDM_GETORDERARRAY, iCount, (LPARAM)lpiArray);
6650 }
6651 
6652 /***
6653  * DESCRIPTION:
6654  * Retrieves the column width.
6655  *
6656  * PARAMETER(S):
6657  * [I] infoPtr : valid pointer to the listview structure
6658  * [I] int : column index
6659  *
6660  * RETURN:
6661  *   SUCCESS : column width
6662  *   FAILURE : zero
6663  */
6664 static INT LISTVIEW_GetColumnWidth(const LISTVIEW_INFO *infoPtr, INT nColumn)
6665 {
6666     INT nColumnWidth = 0;
6667     HDITEMW hdItem;
6668 
6669     TRACE("nColumn=%d\n", nColumn);
6670 
6671     /* we have a 'column' in LIST and REPORT mode only */
6672     switch(infoPtr->uView)
6673     {
6674     case LV_VIEW_LIST:
6675 	nColumnWidth = infoPtr->nItemWidth;
6676 	break;
6677     case LV_VIEW_DETAILS:
6678 	/* We are not using LISTVIEW_GetHeaderRect as this data is updated only after a HDN_ITEMCHANGED.
6679 	 * There is an application that subclasses the listview, calls LVM_GETCOLUMNWIDTH in the
6680 	 * HDN_ITEMCHANGED handler and goes into infinite recursion if it receives old data.
6681 	 */
6682 	hdItem.mask = HDI_WIDTH;
6683 	if (!SendMessageW(infoPtr->hwndHeader, HDM_GETITEMW, nColumn, (LPARAM)&hdItem))
6684 	{
6685 	    WARN("(%p): HDM_GETITEMW failed for item %d\n", infoPtr->hwndSelf, nColumn);
6686 	    return 0;
6687 	}
6688 	nColumnWidth = hdItem.cxy;
6689 	break;
6690     }
6691 
6692     TRACE("nColumnWidth=%d\n", nColumnWidth);
6693     return nColumnWidth;
6694 }
6695 
6696 /***
6697  * DESCRIPTION:
6698  * In list or report display mode, retrieves the number of items that can fit
6699  * vertically in the visible area. In icon or small icon display mode,
6700  * retrieves the total number of visible items.
6701  *
6702  * PARAMETER(S):
6703  * [I] infoPtr : valid pointer to the listview structure
6704  *
6705  * RETURN:
6706  * Number of fully visible items.
6707  */
6708 static INT LISTVIEW_GetCountPerPage(const LISTVIEW_INFO *infoPtr)
6709 {
6710     switch (infoPtr->uView)
6711     {
6712     case LV_VIEW_ICON:
6713     case LV_VIEW_SMALLICON:
6714 	return infoPtr->nItemCount;
6715     case LV_VIEW_DETAILS:
6716 	return LISTVIEW_GetCountPerColumn(infoPtr);
6717     case LV_VIEW_LIST:
6718 	return LISTVIEW_GetCountPerRow(infoPtr) * LISTVIEW_GetCountPerColumn(infoPtr);
6719     }
6720     assert(FALSE);
6721     return 0;
6722 }
6723 
6724 /***
6725  * DESCRIPTION:
6726  * Retrieves an image list handle.
6727  *
6728  * PARAMETER(S):
6729  * [I] infoPtr : valid pointer to the listview structure
6730  * [I] nImageList : image list identifier
6731  *
6732  * RETURN:
6733  *   SUCCESS : image list handle
6734  *   FAILURE : NULL
6735  */
6736 static HIMAGELIST LISTVIEW_GetImageList(const LISTVIEW_INFO *infoPtr, INT nImageList)
6737 {
6738     switch (nImageList)
6739     {
6740     case LVSIL_NORMAL: return infoPtr->himlNormal;
6741     case LVSIL_SMALL:  return infoPtr->himlSmall;
6742     case LVSIL_STATE:  return infoPtr->himlState;
6743     case LVSIL_GROUPHEADER:
6744         FIXME("LVSIL_GROUPHEADER not supported\n");
6745         break;
6746     default:
6747         WARN("got unknown imagelist index - %d\n", nImageList);
6748     }
6749     return NULL;
6750 }
6751 
6752 /* LISTVIEW_GetISearchString */
6753 
6754 /***
6755  * DESCRIPTION:
6756  * Retrieves item attributes.
6757  *
6758  * PARAMETER(S):
6759  * [I] hwnd : window handle
6760  * [IO] lpLVItem : item info
6761  * [I] isW : if TRUE, then lpLVItem is a LPLVITEMW,
6762  *           if FALSE, then lpLVItem is a LPLVITEMA.
6763  *
6764  * NOTE:
6765  *   This is the internal 'GetItem' interface -- it tries to
6766  *   be smart and avoid text copies, if possible, by modifying
6767  *   lpLVItem->pszText to point to the text string. Please note
6768  *   that this is not always possible (e.g. OWNERDATA), so on
6769  *   entry you *must* supply valid values for pszText, and cchTextMax.
6770  *   The only difference to the documented interface is that upon
6771  *   return, you should use *only* the lpLVItem->pszText, rather than
6772  *   the buffer pointer you provided on input. Most code already does
6773  *   that, so it's not a problem.
6774  *   For the two cases when the text must be copied (that is,
6775  *   for LVM_GETITEM, and LVM_GETITEMTEXT), use LISTVIEW_GetItemExtT.
6776  *
6777  * RETURN:
6778  *   SUCCESS : TRUE
6779  *   FAILURE : FALSE
6780  */
6781 static BOOL LISTVIEW_GetItemT(const LISTVIEW_INFO *infoPtr, LPLVITEMW lpLVItem, BOOL isW)
6782 {
6783     ITEMHDR callbackHdr = { LPSTR_TEXTCALLBACKW, I_IMAGECALLBACK };
6784     NMLVDISPINFOW dispInfo;
6785     ITEM_INFO *lpItem;
6786     ITEMHDR* pItemHdr;
6787     HDPA hdpaSubItems;
6788     INT isubitem;
6789 
6790     TRACE("(item=%s, isW=%d)\n", debuglvitem_t(lpLVItem, isW), isW);
6791 
6792     if (!lpLVItem || lpLVItem->iItem < 0 || lpLVItem->iItem >= infoPtr->nItemCount)
6793 	return FALSE;
6794 
6795     if (lpLVItem->mask == 0) return TRUE;
6796     TRACE("mask=%x\n", lpLVItem->mask);
6797 
6798     /* make a local copy */
6799     isubitem = lpLVItem->iSubItem;
6800 
6801     if (isubitem && (lpLVItem->mask & LVIF_STATE))
6802         lpLVItem->state = 0;
6803 
6804     /* a quick optimization if all we're asked is the focus state
6805      * these queries are worth optimising since they are common,
6806      * and can be answered in constant time, without the heavy accesses */
6807     if ( (lpLVItem->mask == LVIF_STATE) && (lpLVItem->stateMask == LVIS_FOCUSED) &&
6808 	 !(infoPtr->uCallbackMask & LVIS_FOCUSED) )
6809     {
6810         lpLVItem->state = 0;
6811         if (infoPtr->nFocusedItem == lpLVItem->iItem && isubitem == 0)
6812             lpLVItem->state |= LVIS_FOCUSED;
6813         return TRUE;
6814     }
6815 
6816     ZeroMemory(&dispInfo, sizeof(dispInfo));
6817 
6818     /* if the app stores all the data, handle it separately */
6819     if (infoPtr->dwStyle & LVS_OWNERDATA)
6820     {
6821 	dispInfo.item.state = 0;
6822 
6823 	/* apparently, we should not callback for lParam in LVS_OWNERDATA */
6824 	if ((lpLVItem->mask & ~(LVIF_STATE | LVIF_PARAM)) ||
6825 	   ((lpLVItem->mask & LVIF_STATE) && (infoPtr->uCallbackMask & lpLVItem->stateMask)))
6826 	{
6827 	    UINT mask = lpLVItem->mask;
6828 
6829 	    /* NOTE: copy only fields which we _know_ are initialized, some apps
6830 	     *       depend on the uninitialized fields being 0 */
6831 	    dispInfo.item.mask = lpLVItem->mask & ~LVIF_PARAM;
6832 	    dispInfo.item.iItem = lpLVItem->iItem;
6833 	    dispInfo.item.iSubItem = isubitem;
6834 	    if (lpLVItem->mask & LVIF_TEXT)
6835 	    {
6836 		if (lpLVItem->mask & LVIF_NORECOMPUTE)
6837 		    /* reset mask */
6838 		    dispInfo.item.mask &= ~(LVIF_TEXT | LVIF_NORECOMPUTE);
6839 		else
6840 		{
6841 		    dispInfo.item.pszText = lpLVItem->pszText;
6842 		    dispInfo.item.cchTextMax = lpLVItem->cchTextMax;
6843 		}
6844 	    }
6845 	    if (lpLVItem->mask & LVIF_STATE)
6846 	        dispInfo.item.stateMask = lpLVItem->stateMask & infoPtr->uCallbackMask;
6847 	    /* could be zeroed on LVIF_NORECOMPUTE case */
6848 	    if (dispInfo.item.mask)
6849 	    {
6850 	        notify_dispinfoT(infoPtr, LVN_GETDISPINFOW, &dispInfo, isW);
6851 	        dispInfo.item.stateMask = lpLVItem->stateMask;
6852 	        if (lpLVItem->mask & (LVIF_GROUPID|LVIF_COLUMNS))
6853 	        {
6854 	            /* full size structure expected - _WIN32IE >= 0x560 */
6855 	            *lpLVItem = dispInfo.item;
6856 	        }
6857 	        else if (lpLVItem->mask & LVIF_INDENT)
6858 	        {
6859 	            /* indent member expected - _WIN32IE >= 0x300 */
6860 	            memcpy(lpLVItem, &dispInfo.item, offsetof( LVITEMW, iGroupId ));
6861 	        }
6862 	        else
6863 	        {
6864 	            /* minimal structure expected */
6865 	            memcpy(lpLVItem, &dispInfo.item, offsetof( LVITEMW, iIndent ));
6866 	        }
6867 	        lpLVItem->mask = mask;
6868 	        TRACE("   getdispinfo(1):lpLVItem=%s\n", debuglvitem_t(lpLVItem, isW));
6869 	    }
6870 	}
6871 
6872 	/* make sure lParam is zeroed out */
6873 	if (lpLVItem->mask & LVIF_PARAM) lpLVItem->lParam = 0;
6874 
6875 	/* callback marked pointer required here */
6876 	if ((lpLVItem->mask & LVIF_TEXT) && (lpLVItem->mask & LVIF_NORECOMPUTE))
6877 	    lpLVItem->pszText = LPSTR_TEXTCALLBACKW;
6878 
6879 	/* we store only a little state, so if we're not asked, we're done */
6880 	if (!(lpLVItem->mask & LVIF_STATE) || isubitem) return TRUE;
6881 
6882 	/* if focus is handled by us, report it */
6883 	if ( lpLVItem->stateMask & ~infoPtr->uCallbackMask & LVIS_FOCUSED )
6884 	{
6885 	    lpLVItem->state &= ~LVIS_FOCUSED;
6886 	    if (infoPtr->nFocusedItem == lpLVItem->iItem)
6887 	        lpLVItem->state |= LVIS_FOCUSED;
6888         }
6889 
6890 	/* and do the same for selection, if we handle it */
6891 	if ( lpLVItem->stateMask & ~infoPtr->uCallbackMask & LVIS_SELECTED )
6892 	{
6893 	    lpLVItem->state &= ~LVIS_SELECTED;
6894 	    if (ranges_contain(infoPtr->selectionRanges, lpLVItem->iItem))
6895 		lpLVItem->state |= LVIS_SELECTED;
6896 	}
6897 
6898 	return TRUE;
6899     }
6900 
6901     /* find the item and subitem structures before we proceed */
6902     hdpaSubItems = DPA_GetPtr(infoPtr->hdpaItems, lpLVItem->iItem);
6903     lpItem = DPA_GetPtr(hdpaSubItems, 0);
6904     assert (lpItem);
6905 
6906     if (isubitem)
6907     {
6908         SUBITEM_INFO *lpSubItem = LISTVIEW_GetSubItemPtr(hdpaSubItems, isubitem);
6909         pItemHdr = lpSubItem ? &lpSubItem->hdr : &callbackHdr;
6910         if (!lpSubItem)
6911         {
6912             WARN(" iSubItem invalid (%08x), ignored.\n", isubitem);
6913             isubitem = 0;
6914         }
6915     }
6916     else
6917 	pItemHdr = &lpItem->hdr;
6918 
6919     /* Do we need to query the state from the app? */
6920     if ((lpLVItem->mask & LVIF_STATE) && infoPtr->uCallbackMask && isubitem == 0)
6921     {
6922 	dispInfo.item.mask |= LVIF_STATE;
6923 	dispInfo.item.stateMask = infoPtr->uCallbackMask;
6924     }
6925 
6926     /* Do we need to enquire about the image? */
6927     if ((lpLVItem->mask & LVIF_IMAGE) && pItemHdr->iImage == I_IMAGECALLBACK &&
6928         (isubitem == 0 || (infoPtr->dwLvExStyle & LVS_EX_SUBITEMIMAGES)))
6929     {
6930 	dispInfo.item.mask |= LVIF_IMAGE;
6931         dispInfo.item.iImage = I_IMAGECALLBACK;
6932     }
6933 
6934     /* Only items support indentation */
6935     if ((lpLVItem->mask & LVIF_INDENT) && lpItem->iIndent == I_INDENTCALLBACK &&
6936         (isubitem == 0))
6937     {
6938         dispInfo.item.mask |= LVIF_INDENT;
6939         dispInfo.item.iIndent = I_INDENTCALLBACK;
6940     }
6941 
6942     /* Apps depend on calling back for text if it is NULL or LPSTR_TEXTCALLBACKW */
6943     if ((lpLVItem->mask & LVIF_TEXT) && !(lpLVItem->mask & LVIF_NORECOMPUTE) &&
6944         !is_text(pItemHdr->pszText))
6945     {
6946 	dispInfo.item.mask |= LVIF_TEXT;
6947 	dispInfo.item.pszText = lpLVItem->pszText;
6948 	dispInfo.item.cchTextMax = lpLVItem->cchTextMax;
6949 	if (dispInfo.item.pszText && dispInfo.item.cchTextMax > 0)
6950 	    *dispInfo.item.pszText = '\0';
6951     }
6952 
6953     /* If we don't have all the requested info, query the application */
6954     if (dispInfo.item.mask)
6955     {
6956 	dispInfo.item.iItem = lpLVItem->iItem;
6957 	dispInfo.item.iSubItem = lpLVItem->iSubItem; /* yes: the original subitem */
6958 	dispInfo.item.lParam = lpItem->lParam;
6959 	notify_dispinfoT(infoPtr, LVN_GETDISPINFOW, &dispInfo, isW);
6960 	TRACE("   getdispinfo(2):item=%s\n", debuglvitem_t(&dispInfo.item, isW));
6961     }
6962 
6963     /* we should not store values for subitems */
6964     if (isubitem) dispInfo.item.mask &= ~LVIF_DI_SETITEM;
6965 
6966     /* Now, handle the iImage field */
6967     if (dispInfo.item.mask & LVIF_IMAGE)
6968     {
6969 	lpLVItem->iImage = dispInfo.item.iImage;
6970 	if ((dispInfo.item.mask & LVIF_DI_SETITEM) && pItemHdr->iImage == I_IMAGECALLBACK)
6971 	    pItemHdr->iImage = dispInfo.item.iImage;
6972     }
6973     else if (lpLVItem->mask & LVIF_IMAGE)
6974     {
6975         if(isubitem == 0 || (infoPtr->dwLvExStyle & LVS_EX_SUBITEMIMAGES))
6976             lpLVItem->iImage = pItemHdr->iImage;
6977         else
6978             lpLVItem->iImage = 0;
6979     }
6980 
6981     /* The pszText field */
6982     if (dispInfo.item.mask & LVIF_TEXT)
6983     {
6984 	if ((dispInfo.item.mask & LVIF_DI_SETITEM) && pItemHdr->pszText)
6985 	    textsetptrT(&pItemHdr->pszText, dispInfo.item.pszText, isW);
6986 
6987 	lpLVItem->pszText = dispInfo.item.pszText;
6988     }
6989     else if (lpLVItem->mask & LVIF_TEXT)
6990     {
6991 	/* if LVN_GETDISPINFO's disabled with LVIF_NORECOMPUTE return callback placeholder */
6992 	if (isW || !is_text(pItemHdr->pszText)) lpLVItem->pszText = pItemHdr->pszText;
6993 	else textcpynT(lpLVItem->pszText, isW, pItemHdr->pszText, TRUE, lpLVItem->cchTextMax);
6994     }
6995 
6996     /* Next is the lParam field */
6997     if (dispInfo.item.mask & LVIF_PARAM)
6998     {
6999 	lpLVItem->lParam = dispInfo.item.lParam;
7000 	if ((dispInfo.item.mask & LVIF_DI_SETITEM))
7001 	    lpItem->lParam = dispInfo.item.lParam;
7002     }
7003     else if (lpLVItem->mask & LVIF_PARAM)
7004 	lpLVItem->lParam = lpItem->lParam;
7005 
7006     /* if this is a subitem, we're done */
7007     if (isubitem) return TRUE;
7008 
7009     /* ... the state field (this one is different due to uCallbackmask) */
7010     if (lpLVItem->mask & LVIF_STATE)
7011     {
7012 	lpLVItem->state = lpItem->state & lpLVItem->stateMask;
7013 	if (dispInfo.item.mask & LVIF_STATE)
7014 	{
7015 	    lpLVItem->state &= ~dispInfo.item.stateMask;
7016 	    lpLVItem->state |= (dispInfo.item.state & dispInfo.item.stateMask);
7017 	}
7018 	if ( lpLVItem->stateMask & ~infoPtr->uCallbackMask & LVIS_FOCUSED )
7019 	{
7020 	    lpLVItem->state &= ~LVIS_FOCUSED;
7021 	    if (infoPtr->nFocusedItem == lpLVItem->iItem)
7022 	        lpLVItem->state |= LVIS_FOCUSED;
7023         }
7024 	if ( lpLVItem->stateMask & ~infoPtr->uCallbackMask & LVIS_SELECTED )
7025 	{
7026 	    lpLVItem->state &= ~LVIS_SELECTED;
7027 	    if (ranges_contain(infoPtr->selectionRanges, lpLVItem->iItem))
7028 		lpLVItem->state |= LVIS_SELECTED;
7029 	}
7030     }
7031 
7032     /* and last, but not least, the indent field */
7033     if (dispInfo.item.mask & LVIF_INDENT)
7034     {
7035 	lpLVItem->iIndent = dispInfo.item.iIndent;
7036 	if ((dispInfo.item.mask & LVIF_DI_SETITEM) && lpItem->iIndent == I_INDENTCALLBACK)
7037 	    lpItem->iIndent = dispInfo.item.iIndent;
7038     }
7039     else if (lpLVItem->mask & LVIF_INDENT)
7040     {
7041         lpLVItem->iIndent = lpItem->iIndent;
7042     }
7043 
7044     return TRUE;
7045 }
7046 
7047 /***
7048  * DESCRIPTION:
7049  * Retrieves item attributes.
7050  *
7051  * PARAMETER(S):
7052  * [I] hwnd : window handle
7053  * [IO] lpLVItem : item info
7054  * [I] isW : if TRUE, then lpLVItem is a LPLVITEMW,
7055  *           if FALSE, then lpLVItem is a LPLVITEMA.
7056  *
7057  * NOTE:
7058  *   This is the external 'GetItem' interface -- it properly copies
7059  *   the text in the provided buffer.
7060  *
7061  * RETURN:
7062  *   SUCCESS : TRUE
7063  *   FAILURE : FALSE
7064  */
7065 static BOOL LISTVIEW_GetItemExtT(const LISTVIEW_INFO *infoPtr, LPLVITEMW lpLVItem, BOOL isW)
7066 {
7067     LPWSTR pszText;
7068     BOOL bResult;
7069 
7070     if (!lpLVItem || lpLVItem->iItem < 0 || lpLVItem->iItem >= infoPtr->nItemCount)
7071 	return FALSE;
7072 
7073     pszText = lpLVItem->pszText;
7074     bResult = LISTVIEW_GetItemT(infoPtr, lpLVItem, isW);
7075     if (bResult && (lpLVItem->mask & LVIF_TEXT) && lpLVItem->pszText != pszText)
7076     {
7077 	if (lpLVItem->pszText != LPSTR_TEXTCALLBACKW)
7078 	    textcpynT(pszText, isW, lpLVItem->pszText, isW, lpLVItem->cchTextMax);
7079 	else
7080 	    pszText = LPSTR_TEXTCALLBACKW;
7081     }
7082     lpLVItem->pszText = pszText;
7083 
7084     return bResult;
7085 }
7086 
7087 
7088 /***
7089  * DESCRIPTION:
7090  * Retrieves the position (upper-left) of the listview control item.
7091  * Note that for LVS_ICON style, the upper-left is that of the icon
7092  * and not the bounding box.
7093  *
7094  * PARAMETER(S):
7095  * [I] infoPtr : valid pointer to the listview structure
7096  * [I] nItem : item index
7097  * [O] lpptPosition : coordinate information
7098  *
7099  * RETURN:
7100  *   SUCCESS : TRUE
7101  *   FAILURE : FALSE
7102  */
7103 static BOOL LISTVIEW_GetItemPosition(const LISTVIEW_INFO *infoPtr, INT nItem, LPPOINT lpptPosition)
7104 {
7105     POINT Origin;
7106 
7107     TRACE("(nItem=%d, lpptPosition=%p)\n", nItem, lpptPosition);
7108 
7109     if (!lpptPosition || nItem < 0 || nItem >= infoPtr->nItemCount) return FALSE;
7110 
7111     LISTVIEW_GetOrigin(infoPtr, &Origin);
7112     LISTVIEW_GetItemOrigin(infoPtr, nItem, lpptPosition);
7113 
7114     if (infoPtr->uView == LV_VIEW_ICON)
7115     {
7116         lpptPosition->x += (infoPtr->nItemWidth - infoPtr->iconSize.cx) / 2;
7117         lpptPosition->y += ICON_TOP_PADDING;
7118     }
7119     lpptPosition->x += Origin.x;
7120     lpptPosition->y += Origin.y;
7121 
7122     TRACE ("  lpptPosition=%s\n", wine_dbgstr_point(lpptPosition));
7123     return TRUE;
7124 }
7125 
7126 
7127 /***
7128  * DESCRIPTION:
7129  * Retrieves the bounding rectangle for a listview control item.
7130  *
7131  * PARAMETER(S):
7132  * [I] infoPtr : valid pointer to the listview structure
7133  * [I] nItem : item index
7134  * [IO] lprc : bounding rectangle coordinates
7135  *     lprc->left specifies the portion of the item for which the bounding
7136  *     rectangle will be retrieved.
7137  *
7138  *     LVIR_BOUNDS Returns the bounding rectangle of the entire item,
7139  *        including the icon and label.
7140  *         *
7141  *         * For LVS_ICON
7142  *         * Experiment shows that native control returns:
7143  *         *  width = min (48, length of text line)
7144  *         *    .left = position.x - (width - iconsize.cx)/2
7145  *         *    .right = .left + width
7146  *         *  height = #lines of text * ntmHeight + icon height + 8
7147  *         *    .top = position.y - 2
7148  *         *    .bottom = .top + height
7149  *         *  separation between items .y = itemSpacing.cy - height
7150  *         *                           .x = itemSpacing.cx - width
7151  *     LVIR_ICON Returns the bounding rectangle of the icon or small icon.
7152  *         *
7153  *         * For LVS_ICON
7154  *         * Experiment shows that native control returns:
7155  *         *  width = iconSize.cx + 16
7156  *         *    .left = position.x - (width - iconsize.cx)/2
7157  *         *    .right = .left + width
7158  *         *  height = iconSize.cy + 4
7159  *         *    .top = position.y - 2
7160  *         *    .bottom = .top + height
7161  *         *  separation between items .y = itemSpacing.cy - height
7162  *         *                           .x = itemSpacing.cx - width
7163  *     LVIR_LABEL Returns the bounding rectangle of the item text.
7164  *         *
7165  *         * For LVS_ICON
7166  *         * Experiment shows that native control returns:
7167  *         *  width = text length
7168  *         *    .left = position.x - width/2
7169  *         *    .right = .left + width
7170  *         *  height = ntmH * linecount + 2
7171  *         *    .top = position.y + iconSize.cy + 6
7172  *         *    .bottom = .top + height
7173  *         *  separation between items .y = itemSpacing.cy - height
7174  *         *                           .x = itemSpacing.cx - width
7175  *     LVIR_SELECTBOUNDS Returns the union of the LVIR_ICON and LVIR_LABEL
7176  *	rectangles, but excludes columns in report view.
7177  *
7178  * RETURN:
7179  *   SUCCESS : TRUE
7180  *   FAILURE : FALSE
7181  *
7182  * NOTES
7183  *   Note that the bounding rectangle of the label in the LVS_ICON view depends
7184  *   upon whether the window has the focus currently and on whether the item
7185  *   is the one with the focus.  Ensure that the control's record of which
7186  *   item has the focus agrees with the items' records.
7187  */
7188 static BOOL LISTVIEW_GetItemRect(const LISTVIEW_INFO *infoPtr, INT nItem, LPRECT lprc)
7189 {
7190     WCHAR szDispText[DISP_TEXT_SIZE] = { '\0' };
7191     BOOL doLabel = TRUE, oversizedBox = FALSE;
7192     POINT Position, Origin;
7193     LVITEMW lvItem;
7194     LONG mode;
7195 
7196     TRACE("(hwnd=%p, nItem=%d, lprc=%p)\n", infoPtr->hwndSelf, nItem, lprc);
7197 
7198     if (!lprc || nItem < 0 || nItem >= infoPtr->nItemCount) return FALSE;
7199 
7200     LISTVIEW_GetOrigin(infoPtr, &Origin);
7201     LISTVIEW_GetItemOrigin(infoPtr, nItem, &Position);
7202 
7203     /* Be smart and try to figure out the minimum we have to do */
7204     if (lprc->left == LVIR_ICON) doLabel = FALSE;
7205     if (infoPtr->uView == LV_VIEW_DETAILS && lprc->left == LVIR_BOUNDS) doLabel = FALSE;
7206     if (infoPtr->uView == LV_VIEW_ICON && lprc->left != LVIR_ICON &&
7207 	infoPtr->bFocus && LISTVIEW_GetItemState(infoPtr, nItem, LVIS_FOCUSED))
7208 	oversizedBox = TRUE;
7209 
7210     /* get what we need from the item before hand, so we make
7211      * only one request. This can speed up things, if data
7212      * is stored on the app side */
7213     lvItem.mask = 0;
7214     if (infoPtr->uView == LV_VIEW_DETAILS) lvItem.mask |= LVIF_INDENT;
7215     if (doLabel) lvItem.mask |= LVIF_TEXT;
7216     lvItem.iItem = nItem;
7217     lvItem.iSubItem = 0;
7218     lvItem.pszText = szDispText;
7219     lvItem.cchTextMax = DISP_TEXT_SIZE;
7220     if (lvItem.mask && !LISTVIEW_GetItemW(infoPtr, &lvItem)) return FALSE;
7221     /* we got the state already up, simulate it here, to avoid a reget */
7222     if (infoPtr->uView == LV_VIEW_ICON && (lprc->left != LVIR_ICON))
7223     {
7224 	lvItem.mask |= LVIF_STATE;
7225 	lvItem.stateMask = LVIS_FOCUSED;
7226 	lvItem.state = (oversizedBox ? LVIS_FOCUSED : 0);
7227     }
7228 
7229     if (infoPtr->uView == LV_VIEW_DETAILS && (infoPtr->dwLvExStyle & LVS_EX_FULLROWSELECT) && lprc->left == LVIR_SELECTBOUNDS)
7230 	lprc->left = LVIR_BOUNDS;
7231 
7232     mode = lprc->left;
7233     switch(lprc->left)
7234     {
7235     case LVIR_ICON:
7236 	LISTVIEW_GetItemMetrics(infoPtr, &lvItem, NULL, NULL, lprc, NULL, NULL);
7237         break;
7238 
7239     case LVIR_LABEL:
7240 	LISTVIEW_GetItemMetrics(infoPtr, &lvItem, NULL, NULL, NULL, NULL, lprc);
7241         break;
7242 
7243     case LVIR_BOUNDS:
7244 	LISTVIEW_GetItemMetrics(infoPtr, &lvItem, lprc, NULL, NULL, NULL, NULL);
7245         break;
7246 
7247     case LVIR_SELECTBOUNDS:
7248 	LISTVIEW_GetItemMetrics(infoPtr, &lvItem, NULL, lprc, NULL, NULL, NULL);
7249         break;
7250 
7251     default:
7252 	WARN("Unknown value: %d\n", lprc->left);
7253 	return FALSE;
7254     }
7255 
7256     if (infoPtr->uView == LV_VIEW_DETAILS)
7257     {
7258 	if (mode != LVIR_BOUNDS)
7259 	    OffsetRect(lprc, Origin.x + LISTVIEW_GetColumnInfo(infoPtr, 0)->rcHeader.left,
7260 	                     Position.y + Origin.y);
7261 	else
7262 	    OffsetRect(lprc, Origin.x, Position.y + Origin.y);
7263     }
7264     else
7265         OffsetRect(lprc, Position.x + Origin.x, Position.y + Origin.y);
7266 
7267     TRACE(" rect=%s\n", wine_dbgstr_rect(lprc));
7268 
7269     return TRUE;
7270 }
7271 
7272 /***
7273  * DESCRIPTION:
7274  * Retrieves the spacing between listview control items.
7275  *
7276  * PARAMETER(S):
7277  * [I] infoPtr : valid pointer to the listview structure
7278  * [IO] lprc : rectangle to receive the output
7279  *             on input, lprc->top = nSubItem
7280  *                       lprc->left = LVIR_ICON | LVIR_BOUNDS | LVIR_LABEL
7281  *
7282  * NOTE: for subItem = 0, we should return the bounds of the _entire_ item,
7283  *       not only those of the first column.
7284  *
7285  * RETURN:
7286  *     TRUE: success
7287  *     FALSE: failure
7288  */
7289 static BOOL LISTVIEW_GetSubItemRect(const LISTVIEW_INFO *infoPtr, INT item, LPRECT lprc)
7290 {
7291     RECT rect = { 0, 0, 0, 0 };
7292     POINT origin;
7293     INT y;
7294 
7295     if (!lprc) return FALSE;
7296 
7297     TRACE("(item=%d, subitem=%d, type=%d)\n", item, lprc->top, lprc->left);
7298     /* Subitem of '0' means item itself, and this works for all control view modes */
7299     if (lprc->top == 0)
7300         return LISTVIEW_GetItemRect(infoPtr, item, lprc);
7301 
7302     if (infoPtr->uView != LV_VIEW_DETAILS) return FALSE;
7303 
7304     LISTVIEW_GetOrigin(infoPtr, &origin);
7305     /* this works for any item index, no matter if it exists or not */
7306     y = item * infoPtr->nItemHeight + origin.y;
7307 
7308     if (infoPtr->hwndHeader && SendMessageW(infoPtr->hwndHeader, HDM_GETITEMRECT, lprc->top, (LPARAM)&rect))
7309     {
7310         rect.top = 0;
7311         rect.bottom = infoPtr->nItemHeight;
7312     }
7313     else
7314     {
7315         /* Native implementation is broken for this case and garbage is left for left and right fields,
7316            we zero them to get predictable output */
7317         lprc->left = lprc->right = lprc->top = 0;
7318         lprc->bottom = infoPtr->nItemHeight;
7319         OffsetRect(lprc, origin.x, y);
7320         TRACE("return rect %s\n", wine_dbgstr_rect(lprc));
7321         return TRUE;
7322     }
7323 
7324     switch (lprc->left)
7325     {
7326     case LVIR_ICON:
7327     {
7328         /* it doesn't matter if main item actually has an icon, if imagelist is set icon width is returned */
7329         if (infoPtr->himlSmall)
7330             rect.right = rect.left + infoPtr->iconSize.cx;
7331         else
7332             rect.right = rect.left;
7333 
7334         rect.bottom = rect.top + infoPtr->iconSize.cy;
7335         break;
7336     }
7337     case LVIR_LABEL:
7338     case LVIR_BOUNDS:
7339         break;
7340 
7341     default:
7342 	ERR("Unknown bounds=%d\n", lprc->left);
7343 	return FALSE;
7344     }
7345 
7346     OffsetRect(&rect, origin.x, y);
7347     *lprc = rect;
7348     TRACE("return rect %s\n", wine_dbgstr_rect(lprc));
7349 
7350     return TRUE;
7351 }
7352 
7353 /***
7354  * DESCRIPTION:
7355  * Retrieves the spacing between listview control items.
7356  *
7357  * PARAMETER(S):
7358  * [I] infoPtr : valid pointer to the listview structure
7359  * [I] bSmall : flag for small or large icon
7360  *
7361  * RETURN:
7362  * Horizontal + vertical spacing
7363  */
7364 static LONG LISTVIEW_GetItemSpacing(const LISTVIEW_INFO *infoPtr, BOOL bSmall)
7365 {
7366   LONG lResult;
7367 
7368   if (!bSmall)
7369   {
7370     lResult = MAKELONG(infoPtr->iconSpacing.cx, infoPtr->iconSpacing.cy);
7371   }
7372   else
7373   {
7374     if (infoPtr->uView == LV_VIEW_ICON)
7375       lResult = MAKELONG(DEFAULT_COLUMN_WIDTH, GetSystemMetrics(SM_CXSMICON)+HEIGHT_PADDING);
7376     else
7377       lResult = MAKELONG(infoPtr->nItemWidth, infoPtr->nItemHeight);
7378   }
7379   return lResult;
7380 }
7381 
7382 /***
7383  * DESCRIPTION:
7384  * Retrieves the state of a listview control item.
7385  *
7386  * PARAMETER(S):
7387  * [I] infoPtr : valid pointer to the listview structure
7388  * [I] nItem : item index
7389  * [I] uMask : state mask
7390  *
7391  * RETURN:
7392  * State specified by the mask.
7393  */
7394 static UINT LISTVIEW_GetItemState(const LISTVIEW_INFO *infoPtr, INT nItem, UINT uMask)
7395 {
7396     LVITEMW lvItem;
7397 
7398     if (nItem < 0 || nItem >= infoPtr->nItemCount) return 0;
7399 
7400     lvItem.iItem = nItem;
7401     lvItem.iSubItem = 0;
7402     lvItem.mask = LVIF_STATE;
7403     lvItem.stateMask = uMask;
7404     if (!LISTVIEW_GetItemW(infoPtr, &lvItem)) return 0;
7405 
7406     return lvItem.state & uMask;
7407 }
7408 
7409 /***
7410  * DESCRIPTION:
7411  * Retrieves the text of a listview control item or subitem.
7412  *
7413  * PARAMETER(S):
7414  * [I] hwnd : window handle
7415  * [I] nItem : item index
7416  * [IO] lpLVItem : item information
7417  * [I] isW :  TRUE if lpLVItem is Unicode
7418  *
7419  * RETURN:
7420  *   SUCCESS : string length
7421  *   FAILURE : 0
7422  */
7423 static INT LISTVIEW_GetItemTextT(const LISTVIEW_INFO *infoPtr, INT nItem, LPLVITEMW lpLVItem, BOOL isW)
7424 {
7425     if (!lpLVItem || nItem < 0 || nItem >= infoPtr->nItemCount) return 0;
7426 
7427     lpLVItem->mask = LVIF_TEXT;
7428     lpLVItem->iItem = nItem;
7429     if (!LISTVIEW_GetItemExtT(infoPtr, lpLVItem, isW)) return 0;
7430 
7431     return textlenT(lpLVItem->pszText, isW);
7432 }
7433 
7434 /***
7435  * DESCRIPTION:
7436  * Searches for an item based on properties + relationships.
7437  *
7438  * PARAMETER(S):
7439  * [I] infoPtr : valid pointer to the listview structure
7440  * [I] nItem : item index
7441  * [I] uFlags : relationship flag
7442  *
7443  * RETURN:
7444  *   SUCCESS : item index
7445  *   FAILURE : -1
7446  */
7447 static INT LISTVIEW_GetNextItem(const LISTVIEW_INFO *infoPtr, INT nItem, UINT uFlags)
7448 {
7449     UINT uMask = 0;
7450     LVFINDINFOW lvFindInfo;
7451     INT nCountPerColumn;
7452 #ifndef __REACTOS__
7453     INT nCountPerRow;
7454 #endif
7455     INT i;
7456 
7457     TRACE("nItem=%d, uFlags=%x, nItemCount=%d\n", nItem, uFlags, infoPtr->nItemCount);
7458     if (nItem < -1 || nItem >= infoPtr->nItemCount) return -1;
7459 
7460     ZeroMemory(&lvFindInfo, sizeof(lvFindInfo));
7461 
7462     if (uFlags & LVNI_CUT)
7463       uMask |= LVIS_CUT;
7464 
7465     if (uFlags & LVNI_DROPHILITED)
7466       uMask |= LVIS_DROPHILITED;
7467 
7468     if (uFlags & LVNI_FOCUSED)
7469       uMask |= LVIS_FOCUSED;
7470 
7471     if (uFlags & LVNI_SELECTED)
7472       uMask |= LVIS_SELECTED;
7473 
7474     /* if we're asked for the focused item, that's only one,
7475      * so it's worth optimizing */
7476     if (uFlags & LVNI_FOCUSED)
7477     {
7478 	if ((LISTVIEW_GetItemState(infoPtr, infoPtr->nFocusedItem, uMask) & uMask) != uMask) return -1;
7479 	return (infoPtr->nFocusedItem == nItem) ? -1 : infoPtr->nFocusedItem;
7480     }
7481 
7482     if (uFlags & LVNI_ABOVE)
7483     {
7484       if ((infoPtr->uView == LV_VIEW_LIST) || (infoPtr->uView == LV_VIEW_DETAILS))
7485       {
7486         while (nItem >= 0)
7487         {
7488           nItem--;
7489           if ((LISTVIEW_GetItemState(infoPtr, nItem, uMask) & uMask) == uMask)
7490             return nItem;
7491         }
7492       }
7493       else
7494       {
7495 #ifndef __REACTOS__
7496         /* Special case for autoarrange - move 'til the top of a list */
7497         if (is_autoarrange(infoPtr))
7498         {
7499           nCountPerRow = LISTVIEW_GetCountPerRow(infoPtr);
7500           while (nItem - nCountPerRow >= 0)
7501           {
7502             nItem -= nCountPerRow;
7503             if ((LISTVIEW_GetItemState(infoPtr, nItem, uMask) & uMask) == uMask)
7504               return nItem;
7505           }
7506           return -1;
7507         }
7508 #endif
7509         lvFindInfo.flags = LVFI_NEARESTXY;
7510         lvFindInfo.vkDirection = VK_UP;
7511         LISTVIEW_GetItemPosition(infoPtr, nItem, &lvFindInfo.pt);
7512         while ((nItem = LISTVIEW_FindItemW(infoPtr, nItem, &lvFindInfo)) != -1)
7513         {
7514           if ((LISTVIEW_GetItemState(infoPtr, nItem, uMask) & uMask) == uMask)
7515             return nItem;
7516         }
7517       }
7518     }
7519     else if (uFlags & LVNI_BELOW)
7520     {
7521       if ((infoPtr->uView == LV_VIEW_LIST) || (infoPtr->uView == LV_VIEW_DETAILS))
7522       {
7523         while (nItem < infoPtr->nItemCount)
7524         {
7525           nItem++;
7526           if ((LISTVIEW_GetItemState(infoPtr, nItem, uMask) & uMask) == uMask)
7527             return nItem;
7528         }
7529       }
7530       else
7531       {
7532 #ifndef __REACTOS__
7533         /* Special case for autoarrange - move 'til the bottom of a list */
7534         if (is_autoarrange(infoPtr))
7535         {
7536           nCountPerRow = LISTVIEW_GetCountPerRow(infoPtr);
7537           while (nItem + nCountPerRow < infoPtr->nItemCount )
7538           {
7539             nItem += nCountPerRow;
7540             if ((LISTVIEW_GetItemState(infoPtr, nItem, uMask) & uMask) == uMask)
7541               return nItem;
7542           }
7543           return -1;
7544         }
7545 #endif
7546         lvFindInfo.flags = LVFI_NEARESTXY;
7547         lvFindInfo.vkDirection = VK_DOWN;
7548         LISTVIEW_GetItemPosition(infoPtr, nItem, &lvFindInfo.pt);
7549         while ((nItem = LISTVIEW_FindItemW(infoPtr, nItem, &lvFindInfo)) != -1)
7550         {
7551           if ((LISTVIEW_GetItemState(infoPtr, nItem, uMask) & uMask) == uMask)
7552             return nItem;
7553         }
7554       }
7555     }
7556     else if (uFlags & LVNI_TOLEFT)
7557     {
7558       if (infoPtr->uView == LV_VIEW_LIST)
7559       {
7560         nCountPerColumn = LISTVIEW_GetCountPerColumn(infoPtr);
7561         while (nItem - nCountPerColumn >= 0)
7562         {
7563           nItem -= nCountPerColumn;
7564           if ((LISTVIEW_GetItemState(infoPtr, nItem, uMask) & uMask) == uMask)
7565             return nItem;
7566         }
7567       }
7568       else if ((infoPtr->uView == LV_VIEW_SMALLICON) || (infoPtr->uView == LV_VIEW_ICON))
7569       {
7570 #ifndef __REACTOS__
7571         /* Special case for autoarrange - move 'til the beginning of a row */
7572         if (is_autoarrange(infoPtr))
7573         {
7574           nCountPerRow = LISTVIEW_GetCountPerRow(infoPtr);
7575           while (nItem % nCountPerRow > 0)
7576           {
7577             nItem --;
7578             if ((LISTVIEW_GetItemState(infoPtr, nItem, uMask) & uMask) == uMask)
7579               return nItem;
7580           }
7581           return -1;
7582         }
7583 #endif
7584         lvFindInfo.flags = LVFI_NEARESTXY;
7585         lvFindInfo.vkDirection = VK_LEFT;
7586         LISTVIEW_GetItemPosition(infoPtr, nItem, &lvFindInfo.pt);
7587         while ((nItem = LISTVIEW_FindItemW(infoPtr, nItem, &lvFindInfo)) != -1)
7588         {
7589           if ((LISTVIEW_GetItemState(infoPtr, nItem, uMask) & uMask) == uMask)
7590             return nItem;
7591         }
7592       }
7593     }
7594     else if (uFlags & LVNI_TORIGHT)
7595     {
7596       if (infoPtr->uView == LV_VIEW_LIST)
7597       {
7598         nCountPerColumn = LISTVIEW_GetCountPerColumn(infoPtr);
7599         while (nItem + nCountPerColumn < infoPtr->nItemCount)
7600         {
7601           nItem += nCountPerColumn;
7602           if ((LISTVIEW_GetItemState(infoPtr, nItem, uMask) & uMask) == uMask)
7603             return nItem;
7604         }
7605       }
7606       else if ((infoPtr->uView == LV_VIEW_SMALLICON) || (infoPtr->uView == LV_VIEW_ICON))
7607       {
7608 #ifndef __REACTOS__
7609         /* Special case for autoarrange - move 'til the end of a row */
7610         if (is_autoarrange(infoPtr))
7611         {
7612           nCountPerRow = LISTVIEW_GetCountPerRow(infoPtr);
7613           while (nItem % nCountPerRow < nCountPerRow - 1 )
7614           {
7615             nItem ++;
7616             if ((LISTVIEW_GetItemState(infoPtr, nItem, uMask) & uMask) == uMask)
7617               return nItem;
7618           }
7619           return -1;
7620         }
7621 #endif
7622         lvFindInfo.flags = LVFI_NEARESTXY;
7623         lvFindInfo.vkDirection = VK_RIGHT;
7624         LISTVIEW_GetItemPosition(infoPtr, nItem, &lvFindInfo.pt);
7625         while ((nItem = LISTVIEW_FindItemW(infoPtr, nItem, &lvFindInfo)) != -1)
7626         {
7627           if ((LISTVIEW_GetItemState(infoPtr, nItem, uMask) & uMask) == uMask)
7628             return nItem;
7629         }
7630       }
7631     }
7632     else
7633     {
7634       nItem++;
7635 
7636       /* search by index */
7637       for (i = nItem; i < infoPtr->nItemCount; i++)
7638       {
7639         if ((LISTVIEW_GetItemState(infoPtr, i, uMask) & uMask) == uMask)
7640           return i;
7641       }
7642     }
7643 
7644     return -1;
7645 }
7646 
7647 /* LISTVIEW_GetNumberOfWorkAreas */
7648 
7649 /***
7650  * DESCRIPTION:
7651  * Retrieves the origin coordinates when in icon or small icon display mode.
7652  *
7653  * PARAMETER(S):
7654  * [I] infoPtr : valid pointer to the listview structure
7655  * [O] lpptOrigin : coordinate information
7656  *
7657  * RETURN:
7658  *   None.
7659  */
7660 static void LISTVIEW_GetOrigin(const LISTVIEW_INFO *infoPtr, LPPOINT lpptOrigin)
7661 {
7662     INT nHorzPos = 0, nVertPos = 0;
7663     SCROLLINFO scrollInfo;
7664 
7665     scrollInfo.cbSize = sizeof(SCROLLINFO);
7666     scrollInfo.fMask = SIF_POS;
7667 
7668     if (GetScrollInfo(infoPtr->hwndSelf, SB_HORZ, &scrollInfo))
7669 	nHorzPos = scrollInfo.nPos;
7670     if (GetScrollInfo(infoPtr->hwndSelf, SB_VERT, &scrollInfo))
7671 	nVertPos = scrollInfo.nPos;
7672 
7673     TRACE("nHorzPos=%d, nVertPos=%d\n", nHorzPos, nVertPos);
7674 
7675     lpptOrigin->x = infoPtr->rcList.left;
7676     lpptOrigin->y = infoPtr->rcList.top;
7677     if (infoPtr->uView == LV_VIEW_LIST)
7678 	nHorzPos *= infoPtr->nItemWidth;
7679     else if (infoPtr->uView == LV_VIEW_DETAILS)
7680 	nVertPos *= infoPtr->nItemHeight;
7681 
7682     lpptOrigin->x -= nHorzPos;
7683     lpptOrigin->y -= nVertPos;
7684 
7685     TRACE(" origin=%s\n", wine_dbgstr_point(lpptOrigin));
7686 }
7687 
7688 /***
7689  * DESCRIPTION:
7690  * Retrieves the width of a string.
7691  *
7692  * PARAMETER(S):
7693  * [I] hwnd : window handle
7694  * [I] lpszText : text string to process
7695  * [I] isW : TRUE if lpszText is Unicode, FALSE otherwise
7696  *
7697  * RETURN:
7698  *   SUCCESS : string width (in pixels)
7699  *   FAILURE : zero
7700  */
7701 static INT LISTVIEW_GetStringWidthT(const LISTVIEW_INFO *infoPtr, LPCWSTR lpszText, BOOL isW)
7702 {
7703     SIZE stringSize;
7704 
7705     stringSize.cx = 0;
7706     if (is_text(lpszText))
7707     {
7708     	HFONT hFont = infoPtr->hFont ? infoPtr->hFont : infoPtr->hDefaultFont;
7709     	HDC hdc = GetDC(infoPtr->hwndSelf);
7710     	HFONT hOldFont = SelectObject(hdc, hFont);
7711 
7712     	if (isW)
7713   	    GetTextExtentPointW(hdc, lpszText, lstrlenW(lpszText), &stringSize);
7714     	else
7715   	    GetTextExtentPointA(hdc, (LPCSTR)lpszText, lstrlenA((LPCSTR)lpszText), &stringSize);
7716     	SelectObject(hdc, hOldFont);
7717     	ReleaseDC(infoPtr->hwndSelf, hdc);
7718     }
7719     return stringSize.cx;
7720 }
7721 
7722 /***
7723  * DESCRIPTION:
7724  * Determines which listview item is located at the specified position.
7725  *
7726  * PARAMETER(S):
7727  * [I] infoPtr : valid pointer to the listview structure
7728  * [IO] lpht : hit test information
7729  * [I] subitem : fill out iSubItem.
7730  * [I] select : return the index only if the hit selects the item
7731  *
7732  * NOTE:
7733  * (mm 20001022): We must not allow iSubItem to be touched, for
7734  * an app might pass only a structure with space up to iItem!
7735  * (MS Office 97 does that for instance in the file open dialog)
7736  *
7737  * RETURN:
7738  *   SUCCESS : item index
7739  *   FAILURE : -1
7740  */
7741 static INT LISTVIEW_HitTest(const LISTVIEW_INFO *infoPtr, LPLVHITTESTINFO lpht, BOOL subitem, BOOL select)
7742 {
7743     WCHAR szDispText[DISP_TEXT_SIZE] = { '\0' };
7744     RECT rcBox, rcBounds, rcState, rcIcon, rcLabel, rcSearch;
7745     POINT Origin, Position, opt;
7746     BOOL is_fullrow;
7747     LVITEMW lvItem;
7748     ITERATOR i;
7749     INT iItem;
7750 
7751     TRACE("(pt=%s, subitem=%d, select=%d)\n", wine_dbgstr_point(&lpht->pt), subitem, select);
7752 
7753     lpht->flags = 0;
7754     lpht->iItem = -1;
7755     if (subitem) lpht->iSubItem = 0;
7756 
7757     LISTVIEW_GetOrigin(infoPtr, &Origin);
7758 
7759     /* set whole list relation flags */
7760     if (subitem && infoPtr->uView == LV_VIEW_DETAILS)
7761     {
7762         /* LVM_SUBITEMHITTEST checks left bound of possible client area */
7763         if (infoPtr->rcList.left > lpht->pt.x && Origin.x < lpht->pt.x)
7764 	    lpht->flags |= LVHT_TOLEFT;
7765 
7766 	if (lpht->pt.y < infoPtr->rcList.top && lpht->pt.y >= 0)
7767 	    opt.y = lpht->pt.y + infoPtr->rcList.top;
7768 	else
7769 	    opt.y = lpht->pt.y;
7770 
7771 	if (infoPtr->rcList.bottom < opt.y)
7772 	    lpht->flags |= LVHT_BELOW;
7773     }
7774     else
7775     {
7776 	if (infoPtr->rcList.left > lpht->pt.x)
7777 	    lpht->flags |= LVHT_TOLEFT;
7778 	else if (infoPtr->rcList.right < lpht->pt.x)
7779 	    lpht->flags |= LVHT_TORIGHT;
7780 
7781 	if (infoPtr->rcList.top > lpht->pt.y)
7782 	    lpht->flags |= LVHT_ABOVE;
7783 	else if (infoPtr->rcList.bottom < lpht->pt.y)
7784 	    lpht->flags |= LVHT_BELOW;
7785     }
7786 
7787     /* even if item is invalid try to find subitem */
7788     if (infoPtr->uView == LV_VIEW_DETAILS && subitem)
7789     {
7790 	RECT *pRect;
7791 	INT j;
7792 
7793 	opt.x = lpht->pt.x - Origin.x;
7794 
7795 	lpht->iSubItem = -1;
7796 	for (j = 0; j < DPA_GetPtrCount(infoPtr->hdpaColumns); j++)
7797 	{
7798 	    pRect = &LISTVIEW_GetColumnInfo(infoPtr, j)->rcHeader;
7799 
7800 	    if ((opt.x >= pRect->left) && (opt.x < pRect->right))
7801 	    {
7802 		lpht->iSubItem = j;
7803 		break;
7804 	    }
7805 	}
7806 	TRACE("lpht->iSubItem=%d\n", lpht->iSubItem);
7807 
7808 	/* if we're outside horizontal columns bounds there's nothing to test further */
7809 	if (lpht->iSubItem == -1)
7810 	{
7811 	    lpht->iItem = -1;
7812 	    lpht->flags = LVHT_NOWHERE;
7813 	    return -1;
7814 	}
7815     }
7816 
7817     TRACE("lpht->flags=0x%x\n", lpht->flags);
7818     if (lpht->flags) return -1;
7819 
7820     lpht->flags |= LVHT_NOWHERE;
7821 
7822     /* first deal with the large items */
7823     rcSearch.left = lpht->pt.x;
7824     rcSearch.top = lpht->pt.y;
7825     rcSearch.right = rcSearch.left + 1;
7826     rcSearch.bottom = rcSearch.top + 1;
7827 
7828     iterator_frameditems(&i, infoPtr, &rcSearch);
7829     iterator_next(&i); /* go to first item in the sequence */
7830     iItem = i.nItem;
7831     iterator_destroy(&i);
7832 
7833     TRACE("lpht->iItem=%d\n", iItem);
7834     if (iItem == -1) return -1;
7835 
7836     lvItem.mask = LVIF_STATE | LVIF_TEXT;
7837     if (infoPtr->uView == LV_VIEW_DETAILS) lvItem.mask |= LVIF_INDENT;
7838     lvItem.stateMask = LVIS_STATEIMAGEMASK;
7839     if (infoPtr->uView == LV_VIEW_ICON) lvItem.stateMask |= LVIS_FOCUSED;
7840     lvItem.iItem = iItem;
7841     lvItem.iSubItem = subitem ? lpht->iSubItem : 0;
7842     lvItem.pszText = szDispText;
7843     lvItem.cchTextMax = DISP_TEXT_SIZE;
7844     if (!LISTVIEW_GetItemW(infoPtr, &lvItem)) return -1;
7845     if (!infoPtr->bFocus) lvItem.state &= ~LVIS_FOCUSED;
7846 
7847     LISTVIEW_GetItemMetrics(infoPtr, &lvItem, &rcBox, NULL, &rcIcon, &rcState, &rcLabel);
7848     LISTVIEW_GetItemOrigin(infoPtr, iItem, &Position);
7849     opt.x = lpht->pt.x - Position.x - Origin.x;
7850 
7851     if (lpht->pt.y < infoPtr->rcList.top && lpht->pt.y >= 0)
7852 	opt.y = lpht->pt.y - Position.y - Origin.y + infoPtr->rcList.top;
7853     else
7854 	opt.y = lpht->pt.y - Position.y - Origin.y;
7855 
7856     if (infoPtr->uView == LV_VIEW_DETAILS)
7857     {
7858 	rcBounds = rcBox;
7859 	if (infoPtr->dwLvExStyle & LVS_EX_FULLROWSELECT)
7860 	    opt.x = lpht->pt.x - Origin.x;
7861     }
7862     else
7863     {
7864         UnionRect(&rcBounds, &rcIcon, &rcLabel);
7865         UnionRect(&rcBounds, &rcBounds, &rcState);
7866     }
7867     TRACE("rcBounds=%s\n", wine_dbgstr_rect(&rcBounds));
7868     if (!PtInRect(&rcBounds, opt)) return -1;
7869 
7870     /* That's a special case - row rectangle is used as item rectangle and
7871        returned flags contain all item parts. */
7872     is_fullrow = (infoPtr->uView == LV_VIEW_DETAILS) && ((infoPtr->dwLvExStyle & LVS_EX_FULLROWSELECT) || (infoPtr->dwStyle & LVS_OWNERDRAWFIXED));
7873 
7874     if (PtInRect(&rcIcon, opt))
7875 	lpht->flags |= LVHT_ONITEMICON;
7876     else if (PtInRect(&rcLabel, opt))
7877 	lpht->flags |= LVHT_ONITEMLABEL;
7878     else if (infoPtr->himlState && PtInRect(&rcState, opt))
7879 	lpht->flags |= LVHT_ONITEMSTATEICON;
7880     if (is_fullrow && !(lpht->flags & LVHT_ONITEM))
7881     {
7882 	lpht->flags = LVHT_ONITEM | LVHT_ABOVE;
7883     }
7884     if (lpht->flags & LVHT_ONITEM)
7885 	lpht->flags &= ~LVHT_NOWHERE;
7886     TRACE("lpht->flags=0x%x\n", lpht->flags);
7887 
7888     if (select && !is_fullrow)
7889     {
7890         if (infoPtr->uView == LV_VIEW_DETAILS)
7891         {
7892             /* get main item bounds */
7893             lvItem.iSubItem = 0;
7894             LISTVIEW_GetItemMetrics(infoPtr, &lvItem, &rcBox, NULL, &rcIcon, &rcState, &rcLabel);
7895             UnionRect(&rcBounds, &rcIcon, &rcLabel);
7896             UnionRect(&rcBounds, &rcBounds, &rcState);
7897         }
7898         if (!PtInRect(&rcBounds, opt)) iItem = -1;
7899     }
7900     return lpht->iItem = iItem;
7901 }
7902 
7903 /***
7904  * DESCRIPTION:
7905  * Inserts a new item in the listview control.
7906  *
7907  * PARAMETER(S):
7908  * [I] infoPtr : valid pointer to the listview structure
7909  * [I] lpLVItem : item information
7910  * [I] isW : TRUE if lpLVItem is Unicode, FALSE if it's ANSI
7911  *
7912  * RETURN:
7913  *   SUCCESS : new item index
7914  *   FAILURE : -1
7915  */
7916 static INT LISTVIEW_InsertItemT(LISTVIEW_INFO *infoPtr, const LVITEMW *lpLVItem, BOOL isW)
7917 {
7918     INT nItem;
7919     HDPA hdpaSubItems;
7920     NMLISTVIEW nmlv;
7921     ITEM_INFO *lpItem;
7922     ITEM_ID *lpID;
7923     BOOL is_sorted, has_changed;
7924     LVITEMW item;
7925     HWND hwndSelf = infoPtr->hwndSelf;
7926 
7927     TRACE("(item=%s, isW=%d)\n", debuglvitem_t(lpLVItem, isW), isW);
7928 
7929     if (infoPtr->dwStyle & LVS_OWNERDATA) return infoPtr->nItemCount++;
7930 
7931     /* make sure it's an item, and not a subitem; cannot insert a subitem */
7932     if (!lpLVItem || lpLVItem->iSubItem) return -1;
7933 
7934     if (!is_assignable_item(lpLVItem, infoPtr->dwStyle)) return -1;
7935 
7936     if (!(lpItem = Alloc(sizeof(ITEM_INFO)))) return -1;
7937 
7938     /* insert item in listview control data structure */
7939     if ( !(hdpaSubItems = DPA_Create(8)) ) goto fail;
7940     if ( !DPA_SetPtr(hdpaSubItems, 0, lpItem) ) assert (FALSE);
7941 
7942     /* link with id struct */
7943     if (!(lpID = Alloc(sizeof(ITEM_ID)))) goto fail;
7944     lpItem->id = lpID;
7945     lpID->item = hdpaSubItems;
7946     lpID->id = get_next_itemid(infoPtr);
7947     if ( DPA_InsertPtr(infoPtr->hdpaItemIds, infoPtr->nItemCount, lpID) == -1) goto fail;
7948 
7949     is_sorted = (infoPtr->dwStyle & (LVS_SORTASCENDING | LVS_SORTDESCENDING)) &&
7950 	        !(infoPtr->dwStyle & LVS_OWNERDRAWFIXED) && (LPSTR_TEXTCALLBACKW != lpLVItem->pszText);
7951 
7952     if (lpLVItem->iItem < 0 && !is_sorted) return -1;
7953 
7954     /* calculate new item index */
7955     if (is_sorted)
7956     {
7957         HDPA hItem;
7958         ITEM_INFO *item_s;
7959         INT i = 0, cmpv;
7960         WCHAR *textW;
7961 
7962         textW = textdupTtoW(lpLVItem->pszText, isW);
7963 
7964         while (i < infoPtr->nItemCount)
7965         {
7966             hItem  = DPA_GetPtr( infoPtr->hdpaItems, i);
7967             item_s = DPA_GetPtr(hItem, 0);
7968 
7969             cmpv = textcmpWT(item_s->hdr.pszText, textW, TRUE);
7970             if (infoPtr->dwStyle & LVS_SORTDESCENDING) cmpv *= -1;
7971 
7972             if (cmpv >= 0) break;
7973             i++;
7974         }
7975 
7976         textfreeT(textW, isW);
7977 
7978         nItem = i;
7979     }
7980     else
7981         nItem = min(lpLVItem->iItem, infoPtr->nItemCount);
7982 
7983     TRACE("inserting at %d, sorted=%d, count=%d, iItem=%d\n", nItem, is_sorted, infoPtr->nItemCount, lpLVItem->iItem);
7984     nItem = DPA_InsertPtr( infoPtr->hdpaItems, nItem, hdpaSubItems );
7985     if (nItem == -1) goto fail;
7986     infoPtr->nItemCount++;
7987 
7988     /* shift indices first so they don't get tangled */
7989     LISTVIEW_ShiftIndices(infoPtr, nItem, 1);
7990 
7991     /* set the item attributes */
7992     if (lpLVItem->mask & (LVIF_GROUPID|LVIF_COLUMNS))
7993     {
7994         /* full size structure expected - _WIN32IE >= 0x560 */
7995         item = *lpLVItem;
7996     }
7997     else if (lpLVItem->mask & LVIF_INDENT)
7998     {
7999         /* indent member expected - _WIN32IE >= 0x300 */
8000         memcpy(&item, lpLVItem, offsetof( LVITEMW, iGroupId ));
8001     }
8002     else
8003     {
8004         /* minimal structure expected */
8005         memcpy(&item, lpLVItem, offsetof( LVITEMW, iIndent ));
8006     }
8007     item.iItem = nItem;
8008     if (infoPtr->dwLvExStyle & LVS_EX_CHECKBOXES)
8009     {
8010         if (item.mask & LVIF_STATE)
8011         {
8012             item.stateMask |= LVIS_STATEIMAGEMASK;
8013             item.state &= ~LVIS_STATEIMAGEMASK;
8014             item.state |= INDEXTOSTATEIMAGEMASK(1);
8015         }
8016         else
8017         {
8018             item.mask |= LVIF_STATE;
8019             item.stateMask = LVIS_STATEIMAGEMASK;
8020             item.state = INDEXTOSTATEIMAGEMASK(1);
8021         }
8022     }
8023 
8024     if (!set_main_item(infoPtr, &item, TRUE, isW, &has_changed)) goto undo;
8025 
8026     /* make room for the position, if we are in the right mode */
8027     if ((infoPtr->uView == LV_VIEW_SMALLICON) || (infoPtr->uView == LV_VIEW_ICON))
8028     {
8029         if (DPA_InsertPtr(infoPtr->hdpaPosX, nItem, 0) == -1)
8030 	    goto undo;
8031         if (DPA_InsertPtr(infoPtr->hdpaPosY, nItem, 0) == -1)
8032 	{
8033 	    DPA_DeletePtr(infoPtr->hdpaPosX, nItem);
8034 	    goto undo;
8035 	}
8036     }
8037 
8038     /* send LVN_INSERTITEM notification */
8039     memset(&nmlv, 0, sizeof(NMLISTVIEW));
8040     nmlv.iItem = nItem;
8041     nmlv.lParam = lpItem->lParam;
8042     notify_listview(infoPtr, LVN_INSERTITEM, &nmlv);
8043     if (!IsWindow(hwndSelf))
8044 	return -1;
8045 
8046     /* align items (set position of each item) */
8047     if (infoPtr->uView == LV_VIEW_SMALLICON || infoPtr->uView == LV_VIEW_ICON)
8048     {
8049 	POINT pt;
8050 
8051 #ifdef __REACTOS__
8052 	if (infoPtr->dwStyle & LVS_ALIGNLEFT)
8053 	    LISTVIEW_NextIconPosLeft(infoPtr, &pt, nItem);
8054         else
8055 	    LISTVIEW_NextIconPosTop(infoPtr, &pt, nItem);
8056 #else
8057     if (infoPtr->dwStyle & LVS_ALIGNLEFT)
8058 	    LISTVIEW_NextIconPosLeft(infoPtr, &pt);
8059         else
8060 	    LISTVIEW_NextIconPosTop(infoPtr, &pt);
8061 #endif
8062 
8063 	LISTVIEW_MoveIconTo(infoPtr, nItem, &pt, TRUE);
8064     }
8065 
8066     /* now is the invalidation fun */
8067     LISTVIEW_ScrollOnInsert(infoPtr, nItem, 1);
8068     return nItem;
8069 
8070 undo:
8071     LISTVIEW_ShiftIndices(infoPtr, nItem, -1);
8072     LISTVIEW_ShiftFocus(infoPtr, infoPtr->nFocusedItem, nItem, -1);
8073     DPA_DeletePtr(infoPtr->hdpaItems, nItem);
8074     infoPtr->nItemCount--;
8075 fail:
8076     DPA_DeletePtr(hdpaSubItems, 0);
8077     DPA_Destroy (hdpaSubItems);
8078     Free (lpItem);
8079     return -1;
8080 }
8081 
8082 /***
8083  * DESCRIPTION:
8084  * Checks item visibility.
8085  *
8086  * PARAMETER(S):
8087  * [I] infoPtr : valid pointer to the listview structure
8088  * [I] nFirst : item index to check for
8089  *
8090  * RETURN:
8091  *   Item visible : TRUE
8092  *   Item invisible or failure : FALSE
8093  */
8094 static BOOL LISTVIEW_IsItemVisible(const LISTVIEW_INFO *infoPtr, INT nItem)
8095 {
8096     POINT Origin, Position;
8097     RECT rcItem;
8098     HDC hdc;
8099     BOOL ret;
8100 
8101     TRACE("nItem=%d\n", nItem);
8102 
8103     if (nItem < 0 || nItem >= DPA_GetPtrCount(infoPtr->hdpaItems)) return FALSE;
8104 
8105     LISTVIEW_GetOrigin(infoPtr, &Origin);
8106     LISTVIEW_GetItemOrigin(infoPtr, nItem, &Position);
8107     rcItem.left = Position.x + Origin.x;
8108     rcItem.top  = Position.y + Origin.y;
8109     rcItem.right  = rcItem.left + infoPtr->nItemWidth;
8110     rcItem.bottom = rcItem.top + infoPtr->nItemHeight;
8111 
8112     hdc = GetDC(infoPtr->hwndSelf);
8113     if (!hdc) return FALSE;
8114     ret = RectVisible(hdc, &rcItem);
8115     ReleaseDC(infoPtr->hwndSelf, hdc);
8116 
8117     return ret;
8118 }
8119 
8120 /***
8121  * DESCRIPTION:
8122  * Redraws a range of items.
8123  *
8124  * PARAMETER(S):
8125  * [I] infoPtr : valid pointer to the listview structure
8126  * [I] nFirst : first item
8127  * [I] nLast : last item
8128  *
8129  * RETURN:
8130  *   SUCCESS : TRUE
8131  *   FAILURE : FALSE
8132  */
8133 static BOOL LISTVIEW_RedrawItems(const LISTVIEW_INFO *infoPtr, INT nFirst, INT nLast)
8134 {
8135     INT i;
8136 
8137     for (i = max(nFirst, 0); i <= min(nLast, infoPtr->nItemCount - 1); i++)
8138 	LISTVIEW_InvalidateItem(infoPtr, i);
8139 
8140     return TRUE;
8141 }
8142 
8143 /***
8144  * DESCRIPTION:
8145  * Scroll the content of a listview.
8146  *
8147  * PARAMETER(S):
8148  * [I] infoPtr : valid pointer to the listview structure
8149  * [I] dx : horizontal scroll amount in pixels
8150  * [I] dy : vertical scroll amount in pixels
8151  *
8152  * RETURN:
8153  *   SUCCESS : TRUE
8154  *   FAILURE : FALSE
8155  *
8156  * COMMENTS:
8157  *  If the control is in report view (LV_VIEW_DETAILS) the control can
8158  *  be scrolled only in line increments. "dy" will be rounded to the
8159  *  nearest number of pixels that are a whole line. Ex: if line height
8160  *  is 16 and an 8 is passed, the list will be scrolled by 16. If a 7
8161  *  is passed, then the scroll will be 0.  (per MSDN 7/2002)
8162  */
8163 static BOOL LISTVIEW_Scroll(LISTVIEW_INFO *infoPtr, INT dx, INT dy)
8164 {
8165     switch(infoPtr->uView) {
8166     case LV_VIEW_DETAILS:
8167 	dy += (dy < 0 ? -1 : 1) * infoPtr->nItemHeight/2;
8168         dy /= infoPtr->nItemHeight;
8169 	break;
8170     case LV_VIEW_LIST:
8171     	if (dy != 0) return FALSE;
8172 	break;
8173     default: /* icon */
8174 	break;
8175     }
8176 
8177     if (dx != 0) LISTVIEW_HScroll(infoPtr, SB_INTERNAL, dx);
8178     if (dy != 0) LISTVIEW_VScroll(infoPtr, SB_INTERNAL, dy);
8179 
8180     return TRUE;
8181 }
8182 
8183 /***
8184  * DESCRIPTION:
8185  * Sets the background color.
8186  *
8187  * PARAMETER(S):
8188  * [I] infoPtr : valid pointer to the listview structure
8189  * [I] color   : background color
8190  *
8191  * RETURN:
8192  *   SUCCESS : TRUE
8193  *   FAILURE : FALSE
8194  */
8195 static BOOL LISTVIEW_SetBkColor(LISTVIEW_INFO *infoPtr, COLORREF color)
8196 {
8197     TRACE("(color=%x)\n", color);
8198 
8199 #ifdef __REACTOS__
8200     infoPtr->bDefaultBkColor = FALSE;
8201 #endif
8202     if(infoPtr->clrBk != color) {
8203 	if (infoPtr->clrBk != CLR_NONE) DeleteObject(infoPtr->hBkBrush);
8204 	infoPtr->clrBk = color;
8205 	if (color == CLR_NONE)
8206 	    infoPtr->hBkBrush = (HBRUSH)GetClassLongPtrW(infoPtr->hwndSelf, GCLP_HBRBACKGROUND);
8207 	else
8208 	{
8209 	    infoPtr->hBkBrush = CreateSolidBrush(color);
8210 	    infoPtr->dwLvExStyle &= ~LVS_EX_TRANSPARENTBKGND;
8211 	}
8212     }
8213 
8214     return TRUE;
8215 }
8216 
8217 /* LISTVIEW_SetBkImage */
8218 
8219 /*** Helper for {Insert,Set}ColumnT *only* */
8220 static void column_fill_hditem(const LISTVIEW_INFO *infoPtr, HDITEMW *lphdi, INT nColumn,
8221                                const LVCOLUMNW *lpColumn, BOOL isW)
8222 {
8223     if (lpColumn->mask & LVCF_FMT)
8224     {
8225 	/* format member is valid */
8226 	lphdi->mask |= HDI_FORMAT;
8227 
8228 	/* set text alignment (leftmost column must be left-aligned) */
8229         if (nColumn == 0 || (lpColumn->fmt & LVCFMT_JUSTIFYMASK) == LVCFMT_LEFT)
8230             lphdi->fmt |= HDF_LEFT;
8231         else if ((lpColumn->fmt & LVCFMT_JUSTIFYMASK) == LVCFMT_RIGHT)
8232             lphdi->fmt |= HDF_RIGHT;
8233         else if ((lpColumn->fmt & LVCFMT_JUSTIFYMASK) == LVCFMT_CENTER)
8234             lphdi->fmt |= HDF_CENTER;
8235 
8236         if (lpColumn->fmt & LVCFMT_BITMAP_ON_RIGHT)
8237             lphdi->fmt |= HDF_BITMAP_ON_RIGHT;
8238 
8239         if (lpColumn->fmt & LVCFMT_COL_HAS_IMAGES)
8240         {
8241             lphdi->fmt |= HDF_IMAGE;
8242             lphdi->iImage = I_IMAGECALLBACK;
8243         }
8244 
8245         if (lpColumn->fmt & LVCFMT_FIXED_WIDTH)
8246             lphdi->fmt |= HDF_FIXEDWIDTH;
8247     }
8248 
8249     if (lpColumn->mask & LVCF_WIDTH)
8250     {
8251         lphdi->mask |= HDI_WIDTH;
8252         if(lpColumn->cx == LVSCW_AUTOSIZE_USEHEADER)
8253         {
8254             /* make it fill the remainder of the controls width */
8255             RECT rcHeader;
8256             INT item_index;
8257 
8258             for(item_index = 0; item_index < (nColumn - 1); item_index++)
8259 	    {
8260             	LISTVIEW_GetHeaderRect(infoPtr, item_index, &rcHeader);
8261 		lphdi->cxy += rcHeader.right - rcHeader.left;
8262 	    }
8263 
8264             /* retrieve the layout of the header */
8265             GetClientRect(infoPtr->hwndSelf, &rcHeader);
8266             TRACE("start cxy=%d rcHeader=%s\n", lphdi->cxy, wine_dbgstr_rect(&rcHeader));
8267 
8268             lphdi->cxy = (rcHeader.right - rcHeader.left) - lphdi->cxy;
8269         }
8270         else
8271             lphdi->cxy = lpColumn->cx;
8272     }
8273 
8274     if (lpColumn->mask & LVCF_TEXT)
8275     {
8276         lphdi->mask |= HDI_TEXT | HDI_FORMAT;
8277         lphdi->fmt |= HDF_STRING;
8278         lphdi->pszText = lpColumn->pszText;
8279         lphdi->cchTextMax = textlenT(lpColumn->pszText, isW);
8280     }
8281 
8282     if (lpColumn->mask & LVCF_IMAGE)
8283     {
8284         lphdi->mask |= HDI_IMAGE;
8285         lphdi->iImage = lpColumn->iImage;
8286     }
8287 
8288     if (lpColumn->mask & LVCF_ORDER)
8289     {
8290 	lphdi->mask |= HDI_ORDER;
8291 	lphdi->iOrder = lpColumn->iOrder;
8292     }
8293 }
8294 
8295 
8296 /***
8297  * DESCRIPTION:
8298  * Inserts a new column.
8299  *
8300  * PARAMETER(S):
8301  * [I] infoPtr : valid pointer to the listview structure
8302  * [I] nColumn : column index
8303  * [I] lpColumn : column information
8304  * [I] isW : TRUE if lpColumn is Unicode, FALSE otherwise
8305  *
8306  * RETURN:
8307  *   SUCCESS : new column index
8308  *   FAILURE : -1
8309  */
8310 static INT LISTVIEW_InsertColumnT(LISTVIEW_INFO *infoPtr, INT nColumn,
8311                                   const LVCOLUMNW *lpColumn, BOOL isW)
8312 {
8313     COLUMN_INFO *lpColumnInfo;
8314     INT nNewColumn;
8315     HDITEMW hdi;
8316 
8317     TRACE("(nColumn=%d, lpColumn=%s, isW=%d)\n", nColumn, debuglvcolumn_t(lpColumn, isW), isW);
8318 
8319     if (!lpColumn || nColumn < 0) return -1;
8320     nColumn = min(nColumn, DPA_GetPtrCount(infoPtr->hdpaColumns));
8321 
8322     ZeroMemory(&hdi, sizeof(HDITEMW));
8323     column_fill_hditem(infoPtr, &hdi, nColumn, lpColumn, isW);
8324 
8325     /*
8326      * A mask not including LVCF_WIDTH turns into a mask of width, width 10
8327      * (can be seen in SPY) otherwise column never gets added.
8328      */
8329     if (!(lpColumn->mask & LVCF_WIDTH)) {
8330         hdi.mask |= HDI_WIDTH;
8331         hdi.cxy = 10;
8332     }
8333 
8334     /*
8335      * when the iSubItem is available Windows copies it to the header lParam. It seems
8336      * to happen only in LVM_INSERTCOLUMN - not in LVM_SETCOLUMN
8337      */
8338     if (lpColumn->mask & LVCF_SUBITEM)
8339     {
8340         hdi.mask |= HDI_LPARAM;
8341         hdi.lParam = lpColumn->iSubItem;
8342     }
8343 
8344     /* create header if not present */
8345     LISTVIEW_CreateHeader(infoPtr);
8346     if (!(LVS_NOCOLUMNHEADER & infoPtr->dwStyle) &&
8347          (infoPtr->uView == LV_VIEW_DETAILS) && (WS_VISIBLE & infoPtr->dwStyle))
8348     {
8349         ShowWindow(infoPtr->hwndHeader, SW_SHOWNORMAL);
8350     }
8351 
8352     /* insert item in header control */
8353     nNewColumn = SendMessageW(infoPtr->hwndHeader,
8354 		              isW ? HDM_INSERTITEMW : HDM_INSERTITEMA,
8355                               nColumn, (LPARAM)&hdi);
8356     if (nNewColumn == -1) return -1;
8357     if (nNewColumn != nColumn) ERR("nColumn=%d, nNewColumn=%d\n", nColumn, nNewColumn);
8358 
8359     /* create our own column info */
8360     if (!(lpColumnInfo = Alloc(sizeof(COLUMN_INFO)))) goto fail;
8361     if (DPA_InsertPtr(infoPtr->hdpaColumns, nNewColumn, lpColumnInfo) == -1) goto fail;
8362 
8363     if (lpColumn->mask & LVCF_FMT) lpColumnInfo->fmt = lpColumn->fmt;
8364     if (lpColumn->mask & LVCF_MINWIDTH) lpColumnInfo->cxMin = lpColumn->cxMin;
8365     if (!SendMessageW(infoPtr->hwndHeader, HDM_GETITEMRECT, nNewColumn, (LPARAM)&lpColumnInfo->rcHeader))
8366         goto fail;
8367 
8368     /* now we have to actually adjust the data */
8369     if (!(infoPtr->dwStyle & LVS_OWNERDATA) && infoPtr->nItemCount > 0)
8370     {
8371 	SUBITEM_INFO *lpSubItem;
8372 	HDPA hdpaSubItems;
8373 	INT nItem, i;
8374 	LVITEMW item;
8375 	BOOL changed;
8376 
8377 	item.iSubItem = nNewColumn;
8378 	item.mask = LVIF_TEXT | LVIF_IMAGE;
8379 	item.iImage = I_IMAGECALLBACK;
8380 	item.pszText = LPSTR_TEXTCALLBACKW;
8381 
8382 	for (nItem = 0; nItem < infoPtr->nItemCount; nItem++)
8383 	{
8384             hdpaSubItems = DPA_GetPtr(infoPtr->hdpaItems, nItem);
8385 	    for (i = 1; i < DPA_GetPtrCount(hdpaSubItems); i++)
8386 	    {
8387                 lpSubItem = DPA_GetPtr(hdpaSubItems, i);
8388 		if (lpSubItem->iSubItem >= nNewColumn)
8389 		    lpSubItem->iSubItem++;
8390 	    }
8391 
8392 	    /* add new subitem for each item */
8393 	    item.iItem = nItem;
8394 	    set_sub_item(infoPtr, &item, isW, &changed);
8395 	}
8396     }
8397 
8398     /* make space for the new column */
8399     LISTVIEW_ScrollColumns(infoPtr, nNewColumn + 1, lpColumnInfo->rcHeader.right - lpColumnInfo->rcHeader.left);
8400     LISTVIEW_UpdateItemSize(infoPtr);
8401 
8402     return nNewColumn;
8403 
8404 fail:
8405     if (nNewColumn != -1) SendMessageW(infoPtr->hwndHeader, HDM_DELETEITEM, nNewColumn, 0);
8406     if (lpColumnInfo)
8407     {
8408 	DPA_DeletePtr(infoPtr->hdpaColumns, nNewColumn);
8409 	Free(lpColumnInfo);
8410     }
8411     return -1;
8412 }
8413 
8414 /***
8415  * DESCRIPTION:
8416  * Sets the attributes of a header item.
8417  *
8418  * PARAMETER(S):
8419  * [I] infoPtr : valid pointer to the listview structure
8420  * [I] nColumn : column index
8421  * [I] lpColumn : column attributes
8422  * [I] isW: if TRUE, then lpColumn is a LPLVCOLUMNW, else it is a LPLVCOLUMNA
8423  *
8424  * RETURN:
8425  *   SUCCESS : TRUE
8426  *   FAILURE : FALSE
8427  */
8428 static BOOL LISTVIEW_SetColumnT(const LISTVIEW_INFO *infoPtr, INT nColumn,
8429                                 const LVCOLUMNW *lpColumn, BOOL isW)
8430 {
8431     HDITEMW hdi, hdiget;
8432     BOOL bResult;
8433 
8434     TRACE("(nColumn=%d, lpColumn=%s, isW=%d)\n", nColumn, debuglvcolumn_t(lpColumn, isW), isW);
8435 
8436     if (!lpColumn || nColumn < 0 || nColumn >= DPA_GetPtrCount(infoPtr->hdpaColumns)) return FALSE;
8437 
8438     ZeroMemory(&hdi, sizeof(HDITEMW));
8439     if (lpColumn->mask & LVCF_FMT)
8440     {
8441         hdi.mask |= HDI_FORMAT;
8442         hdiget.mask = HDI_FORMAT;
8443         if (SendMessageW(infoPtr->hwndHeader, HDM_GETITEMW, nColumn, (LPARAM)&hdiget))
8444 	    hdi.fmt = hdiget.fmt & HDF_STRING;
8445     }
8446     column_fill_hditem(infoPtr, &hdi, nColumn, lpColumn, isW);
8447 
8448     /* set header item attributes */
8449     bResult = SendMessageW(infoPtr->hwndHeader, isW ? HDM_SETITEMW : HDM_SETITEMA, nColumn, (LPARAM)&hdi);
8450     if (!bResult) return FALSE;
8451 
8452     if (lpColumn->mask & LVCF_FMT)
8453     {
8454 	COLUMN_INFO *lpColumnInfo = LISTVIEW_GetColumnInfo(infoPtr, nColumn);
8455 	INT oldFmt = lpColumnInfo->fmt;
8456 
8457 	lpColumnInfo->fmt = lpColumn->fmt;
8458 	if ((oldFmt ^ lpColumn->fmt) & (LVCFMT_JUSTIFYMASK | LVCFMT_IMAGE))
8459 	{
8460 	    if (infoPtr->uView == LV_VIEW_DETAILS) LISTVIEW_InvalidateColumn(infoPtr, nColumn);
8461 	}
8462     }
8463 
8464     if (lpColumn->mask & LVCF_MINWIDTH)
8465 	LISTVIEW_GetColumnInfo(infoPtr, nColumn)->cxMin = lpColumn->cxMin;
8466 
8467     return TRUE;
8468 }
8469 
8470 /***
8471  * DESCRIPTION:
8472  * Sets the column order array
8473  *
8474  * PARAMETERS:
8475  * [I] infoPtr : valid pointer to the listview structure
8476  * [I] iCount : number of elements in column order array
8477  * [I] lpiArray : pointer to column order array
8478  *
8479  * RETURN:
8480  *   SUCCESS : TRUE
8481  *   FAILURE : FALSE
8482  */
8483 static BOOL LISTVIEW_SetColumnOrderArray(LISTVIEW_INFO *infoPtr, INT iCount, const INT *lpiArray)
8484 {
8485     if (!infoPtr->hwndHeader) return FALSE;
8486     infoPtr->colRectsDirty = TRUE;
8487     return SendMessageW(infoPtr->hwndHeader, HDM_SETORDERARRAY, iCount, (LPARAM)lpiArray);
8488 }
8489 
8490 /***
8491  * DESCRIPTION:
8492  * Sets the width of a column
8493  *
8494  * PARAMETERS:
8495  * [I] infoPtr : valid pointer to the listview structure
8496  * [I] nColumn : column index
8497  * [I] cx : column width
8498  *
8499  * RETURN:
8500  *   SUCCESS : TRUE
8501  *   FAILURE : FALSE
8502  */
8503 static BOOL LISTVIEW_SetColumnWidth(LISTVIEW_INFO *infoPtr, INT nColumn, INT cx)
8504 {
8505     WCHAR szDispText[DISP_TEXT_SIZE] = { 0 };
8506     INT max_cx = 0;
8507     HDITEMW hdi;
8508 
8509     TRACE("(nColumn=%d, cx=%d)\n", nColumn, cx);
8510 
8511     /* set column width only if in report or list mode */
8512     if (infoPtr->uView != LV_VIEW_DETAILS && infoPtr->uView != LV_VIEW_LIST) return FALSE;
8513 
8514     /* take care of invalid cx values - LVSCW_AUTOSIZE_* values are negative,
8515        with _USEHEADER being the lowest */
8516     if (infoPtr->uView == LV_VIEW_DETAILS && cx < LVSCW_AUTOSIZE_USEHEADER) cx = LVSCW_AUTOSIZE;
8517     else if (infoPtr->uView == LV_VIEW_LIST && cx <= 0) return FALSE;
8518 
8519     /* resize all columns if in LV_VIEW_LIST mode */
8520     if(infoPtr->uView == LV_VIEW_LIST)
8521     {
8522 	infoPtr->nItemWidth = cx;
8523 	LISTVIEW_InvalidateList(infoPtr);
8524 	return TRUE;
8525     }
8526 
8527     if (nColumn < 0 || nColumn >= DPA_GetPtrCount(infoPtr->hdpaColumns)) return FALSE;
8528 
8529     if (cx == LVSCW_AUTOSIZE || (cx == LVSCW_AUTOSIZE_USEHEADER && nColumn < DPA_GetPtrCount(infoPtr->hdpaColumns) -1))
8530     {
8531 	INT nLabelWidth;
8532 	LVITEMW lvItem;
8533 
8534 	lvItem.mask = LVIF_TEXT;
8535 	lvItem.iItem = 0;
8536 	lvItem.iSubItem = nColumn;
8537 	lvItem.cchTextMax = DISP_TEXT_SIZE;
8538 	for (; lvItem.iItem < infoPtr->nItemCount; lvItem.iItem++)
8539 	{
8540             lvItem.pszText = szDispText;
8541 	    if (!LISTVIEW_GetItemW(infoPtr, &lvItem)) continue;
8542 	    nLabelWidth = LISTVIEW_GetStringWidthT(infoPtr, lvItem.pszText, TRUE);
8543 	    if (max_cx < nLabelWidth) max_cx = nLabelWidth;
8544 	}
8545 	if (infoPtr->himlSmall && (nColumn == 0 || (LISTVIEW_GetColumnInfo(infoPtr, nColumn)->fmt & LVCFMT_IMAGE)))
8546 	    max_cx += infoPtr->iconSize.cx;
8547 	max_cx += TRAILING_LABEL_PADDING;
8548         if (nColumn == 0 && (infoPtr->dwLvExStyle & LVS_EX_CHECKBOXES))
8549             max_cx += GetSystemMetrics(SM_CXSMICON);
8550     }
8551 
8552     /* autosize based on listview items width */
8553     if(cx == LVSCW_AUTOSIZE)
8554 	cx = max_cx;
8555     else if(cx == LVSCW_AUTOSIZE_USEHEADER)
8556     {
8557 	/* if iCol is the last column make it fill the remainder of the controls width */
8558         if(nColumn == DPA_GetPtrCount(infoPtr->hdpaColumns) - 1)
8559 	{
8560 	    RECT rcHeader;
8561 	    POINT Origin;
8562 
8563 	    LISTVIEW_GetOrigin(infoPtr, &Origin);
8564 	    LISTVIEW_GetHeaderRect(infoPtr, nColumn, &rcHeader);
8565 
8566 	    cx = infoPtr->rcList.right - Origin.x - rcHeader.left;
8567 	}
8568 	else
8569 	{
8570             /* Despite what the MS docs say, if this is not the last
8571                column, then MS resizes the column to the width of the
8572                largest text string in the column, including headers
8573                and items. This is different from LVSCW_AUTOSIZE in that
8574 	       LVSCW_AUTOSIZE ignores the header string length. */
8575 	    cx = 0;
8576 
8577 	    /* retrieve header text */
8578 	    hdi.mask = HDI_TEXT|HDI_FORMAT|HDI_IMAGE|HDI_BITMAP;
8579 	    hdi.cchTextMax = DISP_TEXT_SIZE;
8580 	    hdi.pszText = szDispText;
8581 	    if (SendMessageW(infoPtr->hwndHeader, HDM_GETITEMW, nColumn, (LPARAM)&hdi))
8582 	    {
8583 		HDC hdc = GetDC(infoPtr->hwndSelf);
8584 		HFONT old_font = SelectObject(hdc, (HFONT)SendMessageW(infoPtr->hwndHeader, WM_GETFONT, 0, 0));
8585 		HIMAGELIST himl = (HIMAGELIST)SendMessageW(infoPtr->hwndHeader, HDM_GETIMAGELIST, 0, 0);
8586 		INT bitmap_margin = 0;
8587 		SIZE size;
8588 
8589 		if (GetTextExtentPoint32W(hdc, hdi.pszText, lstrlenW(hdi.pszText), &size))
8590 		    cx = size.cx + TRAILING_HEADER_PADDING;
8591 
8592 		if (hdi.fmt & (HDF_IMAGE|HDF_BITMAP))
8593 		    bitmap_margin = SendMessageW(infoPtr->hwndHeader, HDM_GETBITMAPMARGIN, 0, 0);
8594 
8595 		if ((hdi.fmt & HDF_IMAGE) && himl)
8596 		{
8597 		    INT icon_cx, icon_cy;
8598 
8599 		    if (!ImageList_GetIconSize(himl, &icon_cx, &icon_cy))
8600 		        cx += icon_cx + 2*bitmap_margin;
8601 		}
8602 		else if (hdi.fmt & HDF_BITMAP)
8603 		{
8604 		    BITMAP bmp;
8605 
8606 		    GetObjectW(hdi.hbm, sizeof(BITMAP), &bmp);
8607 		    cx += bmp.bmWidth + 2*bitmap_margin;
8608 		}
8609 
8610 		SelectObject(hdc, old_font);
8611 		ReleaseDC(infoPtr->hwndSelf, hdc);
8612 	    }
8613 	    cx = max (cx, max_cx);
8614 	}
8615     }
8616 
8617     if (cx < 0) return FALSE;
8618 
8619     /* call header to update the column change */
8620     hdi.mask = HDI_WIDTH;
8621     hdi.cxy = max(cx, LISTVIEW_GetColumnInfo(infoPtr, nColumn)->cxMin);
8622     TRACE("hdi.cxy=%d\n", hdi.cxy);
8623     return SendMessageW(infoPtr->hwndHeader, HDM_SETITEMW, nColumn, (LPARAM)&hdi);
8624 }
8625 
8626 /***
8627  * Creates the checkbox imagelist.  Helper for LISTVIEW_SetExtendedListViewStyle
8628  *
8629  */
8630 static HIMAGELIST LISTVIEW_CreateCheckBoxIL(const LISTVIEW_INFO *infoPtr)
8631 {
8632     HDC hdc_wnd, hdc;
8633     HBITMAP hbm_im, hbm_mask, hbm_orig;
8634     RECT rc;
8635     HBRUSH hbr_white = GetStockObject(WHITE_BRUSH);
8636     HBRUSH hbr_black = GetStockObject(BLACK_BRUSH);
8637     HIMAGELIST himl;
8638 
8639     himl = ImageList_Create(GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON),
8640                             ILC_COLOR | ILC_MASK, 2, 2);
8641     hdc_wnd = GetDC(infoPtr->hwndSelf);
8642     hdc = CreateCompatibleDC(hdc_wnd);
8643     hbm_im = CreateCompatibleBitmap(hdc_wnd, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON));
8644     hbm_mask = CreateBitmap(GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), 1, 1, NULL);
8645     ReleaseDC(infoPtr->hwndSelf, hdc_wnd);
8646 
8647     SetRect(&rc, 0, 0, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON));
8648     hbm_orig = SelectObject(hdc, hbm_mask);
8649     FillRect(hdc, &rc, hbr_white);
8650     InflateRect(&rc, -2, -2);
8651     FillRect(hdc, &rc, hbr_black);
8652 
8653     SelectObject(hdc, hbm_im);
8654     DrawFrameControl(hdc, &rc, DFC_BUTTON, DFCS_BUTTONCHECK | DFCS_MONO);
8655     SelectObject(hdc, hbm_orig);
8656     ImageList_Add(himl, hbm_im, hbm_mask);
8657 
8658     SelectObject(hdc, hbm_im);
8659     DrawFrameControl(hdc, &rc, DFC_BUTTON, DFCS_BUTTONCHECK | DFCS_MONO | DFCS_CHECKED);
8660     SelectObject(hdc, hbm_orig);
8661     ImageList_Add(himl, hbm_im, hbm_mask);
8662 
8663     DeleteObject(hbm_mask);
8664     DeleteObject(hbm_im);
8665     DeleteDC(hdc);
8666 
8667     return himl;
8668 }
8669 
8670 /***
8671  * DESCRIPTION:
8672  * Sets the extended listview style.
8673  *
8674  * PARAMETERS:
8675  * [I] infoPtr : valid pointer to the listview structure
8676  * [I] dwMask : mask
8677  * [I] dwStyle : style
8678  *
8679  * RETURN:
8680  *   SUCCESS : previous style
8681  *   FAILURE : 0
8682  */
8683 static DWORD LISTVIEW_SetExtendedListViewStyle(LISTVIEW_INFO *infoPtr, DWORD mask, DWORD ex_style)
8684 {
8685     DWORD old_ex_style = infoPtr->dwLvExStyle;
8686 
8687     TRACE("mask=0x%08x, ex_style=0x%08x\n", mask, ex_style);
8688 
8689     /* set new style */
8690     if (mask)
8691 	infoPtr->dwLvExStyle = (old_ex_style & ~mask) | (ex_style & mask);
8692     else
8693 	infoPtr->dwLvExStyle = ex_style;
8694 
8695     if((infoPtr->dwLvExStyle ^ old_ex_style) & LVS_EX_CHECKBOXES)
8696     {
8697         HIMAGELIST himl = 0;
8698         if(infoPtr->dwLvExStyle & LVS_EX_CHECKBOXES)
8699         {
8700             LVITEMW item;
8701             item.mask = LVIF_STATE;
8702             item.stateMask = LVIS_STATEIMAGEMASK;
8703             item.state = INDEXTOSTATEIMAGEMASK(1);
8704             LISTVIEW_SetItemState(infoPtr, -1, &item);
8705 
8706             himl = LISTVIEW_CreateCheckBoxIL(infoPtr);
8707             if(!(infoPtr->dwStyle & LVS_SHAREIMAGELISTS))
8708                 ImageList_Destroy(infoPtr->himlState);
8709         }
8710         himl = LISTVIEW_SetImageList(infoPtr, LVSIL_STATE, himl);
8711         /*   checkbox list replaces previous custom list or... */
8712         if(((infoPtr->dwLvExStyle & LVS_EX_CHECKBOXES) &&
8713            !(infoPtr->dwStyle & LVS_SHAREIMAGELISTS)) ||
8714             /* ...previous was checkbox list */
8715             (old_ex_style & LVS_EX_CHECKBOXES))
8716             ImageList_Destroy(himl);
8717     }
8718 
8719     if((infoPtr->dwLvExStyle ^ old_ex_style) & LVS_EX_HEADERDRAGDROP)
8720     {
8721         DWORD style;
8722 
8723         /* if not already created */
8724         LISTVIEW_CreateHeader(infoPtr);
8725 
8726         style = GetWindowLongW(infoPtr->hwndHeader, GWL_STYLE);
8727         if (infoPtr->dwLvExStyle & LVS_EX_HEADERDRAGDROP)
8728             style |= HDS_DRAGDROP;
8729         else
8730             style &= ~HDS_DRAGDROP;
8731         SetWindowLongW(infoPtr->hwndHeader, GWL_STYLE, style);
8732     }
8733 
8734     /* GRIDLINES adds decoration at top so changes sizes */
8735     if((infoPtr->dwLvExStyle ^ old_ex_style) & LVS_EX_GRIDLINES)
8736     {
8737         LISTVIEW_CreateHeader(infoPtr);
8738         LISTVIEW_UpdateSize(infoPtr);
8739     }
8740 
8741     if((infoPtr->dwLvExStyle ^ old_ex_style) & LVS_EX_FULLROWSELECT)
8742     {
8743         LISTVIEW_CreateHeader(infoPtr);
8744     }
8745 
8746     if((infoPtr->dwLvExStyle ^ old_ex_style) & LVS_EX_TRANSPARENTBKGND)
8747     {
8748         if (infoPtr->dwLvExStyle & LVS_EX_TRANSPARENTBKGND)
8749             LISTVIEW_SetBkColor(infoPtr, CLR_NONE);
8750     }
8751 
8752     if((infoPtr->dwLvExStyle ^ old_ex_style) & LVS_EX_HEADERINALLVIEWS)
8753     {
8754         if (infoPtr->dwLvExStyle & LVS_EX_HEADERINALLVIEWS)
8755             LISTVIEW_CreateHeader(infoPtr);
8756         else
8757             ShowWindow(infoPtr->hwndHeader, SW_HIDE);
8758         LISTVIEW_UpdateSize(infoPtr);
8759         LISTVIEW_UpdateScroll(infoPtr);
8760     }
8761 
8762 #ifdef __REACTOS__
8763     if ((infoPtr->dwLvExStyle & LVS_EX_SNAPTOGRID) > (old_ex_style & LVS_EX_SNAPTOGRID))
8764     {
8765         LISTVIEW_Arrange(infoPtr, LVA_SNAPTOGRID);
8766     }
8767 #endif
8768 
8769     LISTVIEW_InvalidateList(infoPtr);
8770     return old_ex_style;
8771 }
8772 
8773 /***
8774  * DESCRIPTION:
8775  * Sets the new hot cursor used during hot tracking and hover selection.
8776  *
8777  * PARAMETER(S):
8778  * [I] infoPtr : valid pointer to the listview structure
8779  * [I] hCursor : the new hot cursor handle
8780  *
8781  * RETURN:
8782  * Returns the previous hot cursor
8783  */
8784 static HCURSOR LISTVIEW_SetHotCursor(LISTVIEW_INFO *infoPtr, HCURSOR hCursor)
8785 {
8786     HCURSOR oldCursor = infoPtr->hHotCursor;
8787 
8788     infoPtr->hHotCursor = hCursor;
8789 
8790     return oldCursor;
8791 }
8792 
8793 
8794 /***
8795  * DESCRIPTION:
8796  * Sets the hot item index.
8797  *
8798  * PARAMETERS:
8799  * [I] infoPtr : valid pointer to the listview structure
8800  * [I] iIndex : index
8801  *
8802  * RETURN:
8803  *   SUCCESS : previous hot item index
8804  *   FAILURE : -1 (no hot item)
8805  */
8806 static INT LISTVIEW_SetHotItem(LISTVIEW_INFO *infoPtr, INT iIndex)
8807 {
8808     INT iOldIndex = infoPtr->nHotItem;
8809 
8810     infoPtr->nHotItem = iIndex;
8811 
8812     return iOldIndex;
8813 }
8814 
8815 
8816 /***
8817  * DESCRIPTION:
8818  * Sets the amount of time the cursor must hover over an item before it is selected.
8819  *
8820  * PARAMETER(S):
8821  * [I] infoPtr : valid pointer to the listview structure
8822  * [I] dwHoverTime : hover time, if -1 the hover time is set to the default
8823  *
8824  * RETURN:
8825  * Returns the previous hover time
8826  */
8827 static DWORD LISTVIEW_SetHoverTime(LISTVIEW_INFO *infoPtr, DWORD dwHoverTime)
8828 {
8829     DWORD oldHoverTime = infoPtr->dwHoverTime;
8830 
8831     infoPtr->dwHoverTime = dwHoverTime;
8832 
8833     return oldHoverTime;
8834 }
8835 
8836 /***
8837  * DESCRIPTION:
8838  * Sets spacing for icons of LVS_ICON style.
8839  *
8840  * PARAMETER(S):
8841  * [I] infoPtr : valid pointer to the listview structure
8842  * [I] cx : horizontal spacing (-1 = system spacing, 0 = autosize)
8843  * [I] cy : vertical spacing (-1 = system spacing, 0 = autosize)
8844  *
8845  * RETURN:
8846  *   MAKELONG(oldcx, oldcy)
8847  */
8848 static DWORD LISTVIEW_SetIconSpacing(LISTVIEW_INFO *infoPtr, INT cx, INT cy)
8849 {
8850     INT iconWidth = 0, iconHeight = 0;
8851     DWORD oldspacing = MAKELONG(infoPtr->iconSpacing.cx, infoPtr->iconSpacing.cy);
8852 
8853     TRACE("requested=(%d,%d)\n", cx, cy);
8854 
8855     /* set to defaults, if instructed to */
8856     if (cx == -1 && cy == -1)
8857     {
8858         infoPtr->autoSpacing = TRUE;
8859         if (infoPtr->himlNormal)
8860             ImageList_GetIconSize(infoPtr->himlNormal, &iconWidth, &iconHeight);
8861         cx = GetSystemMetrics(SM_CXICONSPACING) - GetSystemMetrics(SM_CXICON) + iconWidth;
8862         cy = GetSystemMetrics(SM_CYICONSPACING) - GetSystemMetrics(SM_CYICON) + iconHeight;
8863     }
8864     else
8865         infoPtr->autoSpacing = FALSE;
8866 
8867     /* if 0 then keep width */
8868     if (cx != 0)
8869         infoPtr->iconSpacing.cx = cx;
8870 
8871     /* if 0 then keep height */
8872     if (cy != 0)
8873         infoPtr->iconSpacing.cy = cy;
8874 
8875     TRACE("old=(%d,%d), new=(%d,%d), iconSize=(%d,%d), ntmH=%d\n",
8876           LOWORD(oldspacing), HIWORD(oldspacing), infoPtr->iconSpacing.cx, infoPtr->iconSpacing.cy,
8877 	  infoPtr->iconSize.cx, infoPtr->iconSize.cy,
8878 	  infoPtr->ntmHeight);
8879 
8880     /* these depend on the iconSpacing */
8881     LISTVIEW_UpdateItemSize(infoPtr);
8882 
8883     return oldspacing;
8884 }
8885 
8886 static inline void set_icon_size(SIZE *size, HIMAGELIST himl, BOOL is_small)
8887 {
8888     INT cx, cy;
8889 
8890     if (himl && ImageList_GetIconSize(himl, &cx, &cy))
8891     {
8892 	size->cx = cx;
8893 	size->cy = cy;
8894     }
8895     else
8896     {
8897 	size->cx = GetSystemMetrics(is_small ? SM_CXSMICON : SM_CXICON);
8898 	size->cy = GetSystemMetrics(is_small ? SM_CYSMICON : SM_CYICON);
8899     }
8900 }
8901 
8902 /***
8903  * DESCRIPTION:
8904  * Sets image lists.
8905  *
8906  * PARAMETER(S):
8907  * [I] infoPtr : valid pointer to the listview structure
8908  * [I] nType : image list type
8909  * [I] himl : image list handle
8910  *
8911  * RETURN:
8912  *   SUCCESS : old image list
8913  *   FAILURE : NULL
8914  */
8915 static HIMAGELIST LISTVIEW_SetImageList(LISTVIEW_INFO *infoPtr, INT nType, HIMAGELIST himl)
8916 {
8917     INT oldHeight = infoPtr->nItemHeight;
8918     HIMAGELIST himlOld = 0;
8919 
8920     TRACE("(nType=%d, himl=%p)\n", nType, himl);
8921 
8922     switch (nType)
8923     {
8924     case LVSIL_NORMAL:
8925         himlOld = infoPtr->himlNormal;
8926         infoPtr->himlNormal = himl;
8927         if (infoPtr->uView == LV_VIEW_ICON) set_icon_size(&infoPtr->iconSize, himl, FALSE);
8928         if (infoPtr->autoSpacing)
8929             LISTVIEW_SetIconSpacing(infoPtr, -1, -1);
8930     break;
8931 
8932     case LVSIL_SMALL:
8933         himlOld = infoPtr->himlSmall;
8934         infoPtr->himlSmall = himl;
8935         if (infoPtr->uView != LV_VIEW_ICON) set_icon_size(&infoPtr->iconSize, himl, TRUE);
8936         if (infoPtr->hwndHeader)
8937             SendMessageW(infoPtr->hwndHeader, HDM_SETIMAGELIST, 0, (LPARAM)himl);
8938     break;
8939 
8940     case LVSIL_STATE:
8941         himlOld = infoPtr->himlState;
8942         infoPtr->himlState = himl;
8943         set_icon_size(&infoPtr->iconStateSize, himl, TRUE);
8944         ImageList_SetBkColor(infoPtr->himlState, CLR_NONE);
8945     break;
8946 
8947     default:
8948         ERR("Unknown icon type=%d\n", nType);
8949 	return NULL;
8950     }
8951 
8952     infoPtr->nItemHeight = LISTVIEW_CalculateItemHeight(infoPtr);
8953     if (infoPtr->nItemHeight != oldHeight)
8954         LISTVIEW_UpdateScroll(infoPtr);
8955 
8956     return himlOld;
8957 }
8958 
8959 /***
8960  * DESCRIPTION:
8961  * Preallocates memory (does *not* set the actual count of items !)
8962  *
8963  * PARAMETER(S):
8964  * [I] infoPtr : valid pointer to the listview structure
8965  * [I] nItems : item count (projected number of items to allocate)
8966  * [I] dwFlags : update flags
8967  *
8968  * RETURN:
8969  *   SUCCESS : TRUE
8970  *   FAILURE : FALSE
8971  */
8972 static BOOL LISTVIEW_SetItemCount(LISTVIEW_INFO *infoPtr, INT nItems, DWORD dwFlags)
8973 {
8974     TRACE("(nItems=%d, dwFlags=%x)\n", nItems, dwFlags);
8975 
8976     if (infoPtr->dwStyle & LVS_OWNERDATA)
8977     {
8978 	INT nOldCount = infoPtr->nItemCount;
8979 	infoPtr->nItemCount = nItems;
8980 
8981 	if (nItems < nOldCount)
8982 	{
8983 	    RANGE range = { nItems, nOldCount };
8984 	    ranges_del(infoPtr->selectionRanges, range);
8985 	    if (infoPtr->nFocusedItem >= nItems)
8986 	    {
8987 		LISTVIEW_SetItemFocus(infoPtr, -1);
8988                 infoPtr->nFocusedItem = -1;
8989 		SetRectEmpty(&infoPtr->rcFocus);
8990 	    }
8991 	}
8992 
8993 	LISTVIEW_UpdateScroll(infoPtr);
8994 
8995 	/* the flags are valid only in ownerdata report and list modes */
8996 	if (infoPtr->uView == LV_VIEW_ICON || infoPtr->uView == LV_VIEW_SMALLICON) dwFlags = 0;
8997 
8998 	if (!(dwFlags & LVSICF_NOSCROLL) && infoPtr->nFocusedItem != -1)
8999 	    LISTVIEW_EnsureVisible(infoPtr, infoPtr->nFocusedItem, FALSE);
9000 
9001 	if (!(dwFlags & LVSICF_NOINVALIDATEALL))
9002 	    LISTVIEW_InvalidateList(infoPtr);
9003 	else
9004 	{
9005 	    INT nFrom, nTo;
9006 	    POINT Origin;
9007 	    RECT rcErase;
9008 
9009 	    LISTVIEW_GetOrigin(infoPtr, &Origin);
9010     	    nFrom = min(nOldCount, nItems);
9011 	    nTo = max(nOldCount, nItems);
9012 
9013 	    if (infoPtr->uView == LV_VIEW_DETAILS)
9014 	    {
9015                 SetRect(&rcErase, 0, nFrom * infoPtr->nItemHeight, infoPtr->nItemWidth,
9016                         nTo * infoPtr->nItemHeight);
9017 		OffsetRect(&rcErase, Origin.x, Origin.y);
9018 		if (IntersectRect(&rcErase, &rcErase, &infoPtr->rcList))
9019 		    LISTVIEW_InvalidateRect(infoPtr, &rcErase);
9020 	    }
9021 	    else /* LV_VIEW_LIST */
9022 	    {
9023 		INT nPerCol = LISTVIEW_GetCountPerColumn(infoPtr);
9024 
9025 		rcErase.left = (nFrom / nPerCol) * infoPtr->nItemWidth;
9026 		rcErase.top = (nFrom % nPerCol) * infoPtr->nItemHeight;
9027 		rcErase.right = rcErase.left + infoPtr->nItemWidth;
9028 		rcErase.bottom = nPerCol * infoPtr->nItemHeight;
9029 		OffsetRect(&rcErase, Origin.x, Origin.y);
9030 		if (IntersectRect(&rcErase, &rcErase, &infoPtr->rcList))
9031 		    LISTVIEW_InvalidateRect(infoPtr, &rcErase);
9032 
9033 		rcErase.left = (nFrom / nPerCol + 1) * infoPtr->nItemWidth;
9034 		rcErase.top = 0;
9035 		rcErase.right = (nTo / nPerCol + 1) * infoPtr->nItemWidth;
9036 		rcErase.bottom = nPerCol * infoPtr->nItemHeight;
9037 		OffsetRect(&rcErase, Origin.x, Origin.y);
9038 		if (IntersectRect(&rcErase, &rcErase, &infoPtr->rcList))
9039 		    LISTVIEW_InvalidateRect(infoPtr, &rcErase);
9040 	    }
9041 	}
9042     }
9043     else
9044     {
9045 	/* According to MSDN for non-LVS_OWNERDATA this is just
9046 	 * a performance issue. The control allocates its internal
9047 	 * data structures for the number of items specified. It
9048 	 * cuts down on the number of memory allocations. Therefore
9049 	 * we will just issue a WARN here
9050 	 */
9051 	WARN("for non-ownerdata performance option not implemented.\n");
9052     }
9053 
9054     return TRUE;
9055 }
9056 
9057 /***
9058  * DESCRIPTION:
9059  * Sets the position of an item.
9060  *
9061  * PARAMETER(S):
9062  * [I] infoPtr : valid pointer to the listview structure
9063  * [I] nItem : item index
9064  * [I] pt : coordinate
9065  *
9066  * RETURN:
9067  *   SUCCESS : TRUE
9068  *   FAILURE : FALSE
9069  */
9070 static BOOL LISTVIEW_SetItemPosition(LISTVIEW_INFO *infoPtr, INT nItem, const POINT *pt)
9071 {
9072     POINT Origin, Pt;
9073 
9074     TRACE("(nItem=%d, pt=%s)\n", nItem, wine_dbgstr_point(pt));
9075 
9076     if (!pt || nItem < 0 || nItem >= infoPtr->nItemCount ||
9077 	!(infoPtr->uView == LV_VIEW_ICON || infoPtr->uView == LV_VIEW_SMALLICON)) return FALSE;
9078 
9079 #ifdef __REACTOS__
9080     /* FIXME:  This should really call snap to grid if auto-arrange is enabled
9081        and limit the size of the grid to nItemCount elements */
9082     if (is_autoarrange(infoPtr)) return FALSE;
9083 #endif
9084 
9085     Pt = *pt;
9086     LISTVIEW_GetOrigin(infoPtr, &Origin);
9087 
9088     /* This point value seems to be an undocumented feature.
9089      * The best guess is that it means either at the origin,
9090      * or at true beginning of the list. I will assume the origin. */
9091     if ((Pt.x == -1) && (Pt.y == -1))
9092 	Pt = Origin;
9093 
9094     if (infoPtr->uView == LV_VIEW_ICON)
9095     {
9096 	Pt.x -= (infoPtr->nItemWidth - infoPtr->iconSize.cx) / 2;
9097 	Pt.y -= ICON_TOP_PADDING;
9098     }
9099     Pt.x -= Origin.x;
9100     Pt.y -= Origin.y;
9101 
9102 #ifdef __REACTOS__
9103     if (infoPtr->dwLvExStyle & LVS_EX_SNAPTOGRID)
9104     {
9105         Pt.x = max(0, Pt.x + (infoPtr->nItemWidth >> 1) - (Pt.x + (infoPtr->nItemWidth >> 1)) % infoPtr->nItemWidth);
9106         Pt.y = max(0, Pt.y + (infoPtr->nItemHeight >> 1) - (Pt.y + (infoPtr->nItemHeight >> 1)) % infoPtr->nItemHeight);
9107     }
9108 #endif
9109 
9110     return LISTVIEW_MoveIconTo(infoPtr, nItem, &Pt, FALSE);
9111 }
9112 
9113 /***
9114  * DESCRIPTION:
9115  * Sets the state of one or many items.
9116  *
9117  * PARAMETER(S):
9118  * [I] infoPtr : valid pointer to the listview structure
9119  * [I] nItem : item index
9120  * [I] item  : item or subitem info
9121  *
9122  * RETURN:
9123  *   SUCCESS : TRUE
9124  *   FAILURE : FALSE
9125  */
9126 static BOOL LISTVIEW_SetItemState(LISTVIEW_INFO *infoPtr, INT nItem, const LVITEMW *item)
9127 {
9128     BOOL ret = TRUE;
9129     LVITEMW lvItem;
9130 
9131     if (!item) return FALSE;
9132 
9133     lvItem.iItem = nItem;
9134     lvItem.iSubItem = 0;
9135     lvItem.mask = LVIF_STATE;
9136     lvItem.state = item->state;
9137     lvItem.stateMask = item->stateMask;
9138     TRACE("item=%s\n", debuglvitem_t(&lvItem, TRUE));
9139 
9140     if (nItem == -1)
9141     {
9142         UINT oldstate = 0;
9143         DWORD old_mask;
9144 
9145         /* special case optimization for recurring attempt to deselect all */
9146         if (lvItem.state == 0 && lvItem.stateMask == LVIS_SELECTED && !LISTVIEW_GetSelectedCount(infoPtr))
9147             return TRUE;
9148 
9149 	/* select all isn't allowed in LVS_SINGLESEL */
9150 	if ((lvItem.state & lvItem.stateMask & LVIS_SELECTED) && (infoPtr->dwStyle & LVS_SINGLESEL))
9151 	    return FALSE;
9152 
9153 	/* focus all isn't allowed */
9154 	if (lvItem.state & lvItem.stateMask & LVIS_FOCUSED) return FALSE;
9155 
9156         old_mask = infoPtr->notify_mask & NOTIFY_MASK_ITEM_CHANGE;
9157         if (infoPtr->dwStyle & LVS_OWNERDATA)
9158         {
9159             infoPtr->notify_mask &= ~NOTIFY_MASK_ITEM_CHANGE;
9160             if (!(lvItem.state & LVIS_SELECTED) && LISTVIEW_GetSelectedCount(infoPtr))
9161                 oldstate |= LVIS_SELECTED;
9162             if (infoPtr->nFocusedItem != -1) oldstate |= LVIS_FOCUSED;
9163         }
9164 
9165     	/* apply to all items */
9166     	for (lvItem.iItem = 0; lvItem.iItem < infoPtr->nItemCount; lvItem.iItem++)
9167 	    if (!LISTVIEW_SetItemT(infoPtr, &lvItem, TRUE)) ret = FALSE;
9168 
9169         if (infoPtr->dwStyle & LVS_OWNERDATA)
9170         {
9171             NMLISTVIEW nmlv;
9172 
9173             infoPtr->notify_mask |= old_mask;
9174 
9175             nmlv.iItem = -1;
9176             nmlv.iSubItem = 0;
9177             nmlv.uNewState = lvItem.state & lvItem.stateMask;
9178             nmlv.uOldState = oldstate & lvItem.stateMask;
9179             nmlv.uChanged = LVIF_STATE;
9180             nmlv.ptAction.x = nmlv.ptAction.y = 0;
9181             nmlv.lParam = 0;
9182 
9183             notify_listview(infoPtr, LVN_ITEMCHANGED, &nmlv);
9184         }
9185     }
9186     else
9187 	ret = LISTVIEW_SetItemT(infoPtr, &lvItem, TRUE);
9188 
9189     return ret;
9190 }
9191 
9192 /***
9193  * DESCRIPTION:
9194  * Sets the text of an item or subitem.
9195  *
9196  * PARAMETER(S):
9197  * [I] hwnd : window handle
9198  * [I] nItem : item index
9199  * [I] lpLVItem : item or subitem info
9200  * [I] isW : TRUE if input is Unicode
9201  *
9202  * RETURN:
9203  *   SUCCESS : TRUE
9204  *   FAILURE : FALSE
9205  */
9206 static BOOL LISTVIEW_SetItemTextT(LISTVIEW_INFO *infoPtr, INT nItem, const LVITEMW *lpLVItem, BOOL isW)
9207 {
9208     LVITEMW lvItem;
9209 
9210     if (!lpLVItem || nItem < 0 || nItem >= infoPtr->nItemCount) return FALSE;
9211     if (infoPtr->dwStyle & LVS_OWNERDATA) return FALSE;
9212 
9213     lvItem.iItem = nItem;
9214     lvItem.iSubItem = lpLVItem->iSubItem;
9215     lvItem.mask = LVIF_TEXT;
9216     lvItem.pszText = lpLVItem->pszText;
9217     lvItem.cchTextMax = lpLVItem->cchTextMax;
9218 
9219     TRACE("(nItem=%d, lpLVItem=%s, isW=%d)\n", nItem, debuglvitem_t(&lvItem, isW), isW);
9220 
9221     return LISTVIEW_SetItemT(infoPtr, &lvItem, isW);
9222 }
9223 
9224 /***
9225  * DESCRIPTION:
9226  * Set item index that marks the start of a multiple selection.
9227  *
9228  * PARAMETER(S):
9229  * [I] infoPtr : valid pointer to the listview structure
9230  * [I] nIndex : index
9231  *
9232  * RETURN:
9233  * Index number or -1 if there is no selection mark.
9234  */
9235 static INT LISTVIEW_SetSelectionMark(LISTVIEW_INFO *infoPtr, INT nIndex)
9236 {
9237   INT nOldIndex = infoPtr->nSelectionMark;
9238 
9239   TRACE("(nIndex=%d)\n", nIndex);
9240 
9241   if (nIndex >= -1 && nIndex < infoPtr->nItemCount)
9242     infoPtr->nSelectionMark = nIndex;
9243 
9244   return nOldIndex;
9245 }
9246 
9247 /***
9248  * DESCRIPTION:
9249  * Sets the text background color.
9250  *
9251  * PARAMETER(S):
9252  * [I] infoPtr : valid pointer to the listview structure
9253  * [I] color   : text background color
9254  *
9255  * RETURN:
9256  *   SUCCESS : TRUE
9257  *   FAILURE : FALSE
9258  */
9259 static BOOL LISTVIEW_SetTextBkColor(LISTVIEW_INFO *infoPtr, COLORREF color)
9260 {
9261     TRACE("(color=%x)\n", color);
9262 
9263     infoPtr->clrTextBk = color;
9264     return TRUE;
9265 }
9266 
9267 /***
9268  * DESCRIPTION:
9269  * Sets the text foreground color.
9270  *
9271  * PARAMETER(S):
9272  * [I] infoPtr : valid pointer to the listview structure
9273  * [I] color   : text color
9274  *
9275  * RETURN:
9276  *   SUCCESS : TRUE
9277  *   FAILURE : FALSE
9278  */
9279 static BOOL LISTVIEW_SetTextColor (LISTVIEW_INFO *infoPtr, COLORREF color)
9280 {
9281     TRACE("(color=%x)\n", color);
9282 
9283     infoPtr->clrText = color;
9284     return TRUE;
9285 }
9286 
9287 /***
9288  * DESCRIPTION:
9289  * Sets new ToolTip window to ListView control.
9290  *
9291  * PARAMETER(S):
9292  * [I] infoPtr        : valid pointer to the listview structure
9293  * [I] hwndNewToolTip : handle to new ToolTip
9294  *
9295  * RETURN:
9296  *   old tool tip
9297  */
9298 static HWND LISTVIEW_SetToolTips( LISTVIEW_INFO *infoPtr, HWND hwndNewToolTip)
9299 {
9300   HWND hwndOldToolTip = infoPtr->hwndToolTip;
9301   infoPtr->hwndToolTip = hwndNewToolTip;
9302   return hwndOldToolTip;
9303 }
9304 
9305 /*
9306  * DESCRIPTION:
9307  *   sets the Unicode character format flag for the control
9308  * PARAMETER(S):
9309  *    [I] infoPtr         :valid pointer to the listview structure
9310  *    [I] fUnicode        :true to switch to UNICODE false to switch to ANSI
9311  *
9312  * RETURN:
9313  *    Old Unicode Format
9314  */
9315 static BOOL LISTVIEW_SetUnicodeFormat( LISTVIEW_INFO *infoPtr, BOOL unicode)
9316 {
9317   SHORT rc = infoPtr->notifyFormat;
9318   infoPtr->notifyFormat = (unicode) ? NFR_UNICODE : NFR_ANSI;
9319   return rc == NFR_UNICODE;
9320 }
9321 
9322 /*
9323  * DESCRIPTION:
9324  *   sets the control view mode
9325  * PARAMETER(S):
9326  *    [I] infoPtr         :valid pointer to the listview structure
9327  *    [I] nView           :new view mode value
9328  *
9329  * RETURN:
9330  *    SUCCESS:  1
9331  *    FAILURE: -1
9332  */
9333 static INT LISTVIEW_SetView(LISTVIEW_INFO *infoPtr, DWORD nView)
9334 {
9335   HIMAGELIST himl;
9336 
9337   if (infoPtr->uView == nView) return 1;
9338 
9339   if ((INT)nView < 0 || nView > LV_VIEW_MAX) return -1;
9340   if (nView == LV_VIEW_TILE)
9341   {
9342       FIXME("View LV_VIEW_TILE unimplemented\n");
9343       return -1;
9344   }
9345 
9346   infoPtr->uView = nView;
9347 
9348   SendMessageW(infoPtr->hwndEdit, WM_KILLFOCUS, 0, 0);
9349   ShowWindow(infoPtr->hwndHeader, SW_HIDE);
9350 
9351   ShowScrollBar(infoPtr->hwndSelf, SB_BOTH, FALSE);
9352   SetRectEmpty(&infoPtr->rcFocus);
9353 
9354   himl = (nView == LV_VIEW_ICON ? infoPtr->himlNormal : infoPtr->himlSmall);
9355   set_icon_size(&infoPtr->iconSize, himl, nView != LV_VIEW_ICON);
9356 
9357   switch (nView)
9358   {
9359   case LV_VIEW_ICON:
9360   case LV_VIEW_SMALLICON:
9361       LISTVIEW_Arrange(infoPtr, LVA_DEFAULT);
9362       break;
9363   case LV_VIEW_DETAILS:
9364   {
9365       HDLAYOUT hl;
9366       WINDOWPOS wp;
9367 
9368       LISTVIEW_CreateHeader( infoPtr );
9369 
9370       hl.prc = &infoPtr->rcList;
9371       hl.pwpos = &wp;
9372       SendMessageW(infoPtr->hwndHeader, HDM_LAYOUT, 0, (LPARAM)&hl);
9373       SetWindowPos(infoPtr->hwndHeader, infoPtr->hwndSelf, wp.x, wp.y, wp.cx, wp.cy,
9374                    wp.flags | ((infoPtr->dwStyle & LVS_NOCOLUMNHEADER) ? SWP_HIDEWINDOW : SWP_SHOWWINDOW));
9375       break;
9376   }
9377   case LV_VIEW_LIST:
9378       break;
9379   }
9380 
9381   LISTVIEW_UpdateItemSize(infoPtr);
9382   LISTVIEW_UpdateSize(infoPtr);
9383   LISTVIEW_UpdateScroll(infoPtr);
9384   LISTVIEW_InvalidateList(infoPtr);
9385 
9386   TRACE("nView=%d\n", nView);
9387 
9388   return 1;
9389 }
9390 
9391 /* LISTVIEW_SetWorkAreas */
9392 
9393 /***
9394  * DESCRIPTION:
9395  * Callback internally used by LISTVIEW_SortItems() in response of LVM_SORTITEMS
9396  *
9397  * PARAMETER(S):
9398  * [I] first : pointer to first ITEM_INFO to compare
9399  * [I] second : pointer to second ITEM_INFO to compare
9400  * [I] lParam : HWND of control
9401  *
9402  * RETURN:
9403  *   if first comes before second : negative
9404  *   if first comes after second : positive
9405  *   if first and second are equivalent : zero
9406  */
9407 static INT WINAPI LISTVIEW_CallBackCompare(LPVOID first, LPVOID second, LPARAM lParam)
9408 {
9409   LISTVIEW_INFO *infoPtr = (LISTVIEW_INFO *)lParam;
9410   ITEM_INFO* lv_first = DPA_GetPtr( first, 0 );
9411   ITEM_INFO* lv_second = DPA_GetPtr( second, 0 );
9412 
9413   /* Forward the call to the client defined callback */
9414   return (infoPtr->pfnCompare)( lv_first->lParam , lv_second->lParam, infoPtr->lParamSort );
9415 }
9416 
9417 /***
9418  * DESCRIPTION:
9419  * Callback internally used by LISTVIEW_SortItems() in response of LVM_SORTITEMSEX
9420  *
9421  * PARAMETER(S):
9422  * [I] first : pointer to first ITEM_INFO to compare
9423  * [I] second : pointer to second ITEM_INFO to compare
9424  * [I] lParam : HWND of control
9425  *
9426  * RETURN:
9427  *   if first comes before second : negative
9428  *   if first comes after second : positive
9429  *   if first and second are equivalent : zero
9430  */
9431 static INT WINAPI LISTVIEW_CallBackCompareEx(LPVOID first, LPVOID second, LPARAM lParam)
9432 {
9433   LISTVIEW_INFO *infoPtr = (LISTVIEW_INFO *)lParam;
9434   INT first_idx  = DPA_GetPtrIndex( infoPtr->hdpaItems, first  );
9435   INT second_idx = DPA_GetPtrIndex( infoPtr->hdpaItems, second );
9436 
9437   /* Forward the call to the client defined callback */
9438   return (infoPtr->pfnCompare)( first_idx, second_idx, infoPtr->lParamSort );
9439 }
9440 
9441 /***
9442  * DESCRIPTION:
9443  * Sorts the listview items.
9444  *
9445  * PARAMETER(S):
9446  * [I] infoPtr : valid pointer to the listview structure
9447  * [I] pfnCompare : application-defined value
9448  * [I] lParamSort : pointer to comparison callback
9449  * [I] IsEx : TRUE when LVM_SORTITEMSEX used
9450  *
9451  * RETURN:
9452  *   SUCCESS : TRUE
9453  *   FAILURE : FALSE
9454  */
9455 static BOOL LISTVIEW_SortItems(LISTVIEW_INFO *infoPtr, PFNLVCOMPARE pfnCompare,
9456                                LPARAM lParamSort, BOOL IsEx)
9457 {
9458     HDPA hdpaSubItems;
9459     ITEM_INFO *lpItem;
9460     LPVOID selectionMarkItem = NULL;
9461     LPVOID focusedItem = NULL;
9462     int i;
9463 
9464     TRACE("(pfnCompare=%p, lParamSort=%lx)\n", pfnCompare, lParamSort);
9465 
9466     if (infoPtr->dwStyle & LVS_OWNERDATA) return FALSE;
9467 
9468     if (!pfnCompare) return FALSE;
9469     if (!infoPtr->hdpaItems) return FALSE;
9470 
9471     /* if there are 0 or 1 items, there is no need to sort */
9472     if (infoPtr->nItemCount < 2) return TRUE;
9473 
9474     /* clear selection */
9475     ranges_clear(infoPtr->selectionRanges);
9476 
9477     /* save selection mark and focused item */
9478     if (infoPtr->nSelectionMark >= 0)
9479         selectionMarkItem = DPA_GetPtr(infoPtr->hdpaItems, infoPtr->nSelectionMark);
9480     if (infoPtr->nFocusedItem >= 0)
9481         focusedItem = DPA_GetPtr(infoPtr->hdpaItems, infoPtr->nFocusedItem);
9482 
9483     infoPtr->pfnCompare = pfnCompare;
9484     infoPtr->lParamSort = lParamSort;
9485     if (IsEx)
9486         DPA_Sort(infoPtr->hdpaItems, LISTVIEW_CallBackCompareEx, (LPARAM)infoPtr);
9487     else
9488         DPA_Sort(infoPtr->hdpaItems, LISTVIEW_CallBackCompare, (LPARAM)infoPtr);
9489 
9490     /* restore selection ranges */
9491     for (i=0; i < infoPtr->nItemCount; i++)
9492     {
9493         hdpaSubItems = DPA_GetPtr(infoPtr->hdpaItems, i);
9494         lpItem = DPA_GetPtr(hdpaSubItems, 0);
9495 
9496 	if (lpItem->state & LVIS_SELECTED)
9497 	    ranges_additem(infoPtr->selectionRanges, i);
9498     }
9499     /* restore selection mark and focused item */
9500     infoPtr->nSelectionMark = DPA_GetPtrIndex(infoPtr->hdpaItems, selectionMarkItem);
9501     infoPtr->nFocusedItem   = DPA_GetPtrIndex(infoPtr->hdpaItems, focusedItem);
9502 
9503     /* I believe nHotItem should be left alone, see LISTVIEW_ShiftIndices */
9504 
9505     /* refresh the display */
9506     LISTVIEW_InvalidateList(infoPtr);
9507     return TRUE;
9508 }
9509 
9510 /***
9511  * DESCRIPTION:
9512  * Update theme handle after a theme change.
9513  *
9514  * PARAMETER(S):
9515  * [I] infoPtr : valid pointer to the listview structure
9516  *
9517  * RETURN:
9518  *   SUCCESS : 0
9519  *   FAILURE : something else
9520  */
9521 static LRESULT LISTVIEW_ThemeChanged(const LISTVIEW_INFO *infoPtr)
9522 {
9523     HTHEME theme = GetWindowTheme(infoPtr->hwndSelf);
9524     CloseThemeData(theme);
9525     OpenThemeData(infoPtr->hwndSelf, themeClass);
9526     return 0;
9527 }
9528 
9529 /***
9530  * DESCRIPTION:
9531  * Updates an items or rearranges the listview control.
9532  *
9533  * PARAMETER(S):
9534  * [I] infoPtr : valid pointer to the listview structure
9535  * [I] nItem : item index
9536  *
9537  * RETURN:
9538  *   SUCCESS : TRUE
9539  *   FAILURE : FALSE
9540  */
9541 static BOOL LISTVIEW_Update(LISTVIEW_INFO *infoPtr, INT nItem)
9542 {
9543     TRACE("(nItem=%d)\n", nItem);
9544 
9545     if (nItem < 0 || nItem >= infoPtr->nItemCount) return FALSE;
9546 
9547     /* rearrange with default alignment style */
9548     if (is_autoarrange(infoPtr))
9549 	LISTVIEW_Arrange(infoPtr, LVA_DEFAULT);
9550     else
9551 	LISTVIEW_InvalidateItem(infoPtr, nItem);
9552 
9553     return TRUE;
9554 }
9555 
9556 /***
9557  * DESCRIPTION:
9558  * Draw the track line at the place defined in the infoPtr structure.
9559  * The line is drawn with a XOR pen so drawing the line for the second time
9560  * in the same place erases the line.
9561  *
9562  * PARAMETER(S):
9563  * [I] infoPtr : valid pointer to the listview structure
9564  *
9565  * RETURN:
9566  *   SUCCESS : TRUE
9567  *   FAILURE : FALSE
9568  */
9569 static BOOL LISTVIEW_DrawTrackLine(const LISTVIEW_INFO *infoPtr)
9570 {
9571     HDC hdc;
9572 
9573     if (infoPtr->xTrackLine == -1)
9574         return FALSE;
9575 
9576     if (!(hdc = GetDC(infoPtr->hwndSelf)))
9577         return FALSE;
9578     PatBlt( hdc, infoPtr->xTrackLine, infoPtr->rcList.top,
9579             1, infoPtr->rcList.bottom - infoPtr->rcList.top, DSTINVERT );
9580     ReleaseDC(infoPtr->hwndSelf, hdc);
9581     return TRUE;
9582 }
9583 
9584 /***
9585  * DESCRIPTION:
9586  * Called when an edit control should be displayed. This function is called after
9587  * we are sure that there was a single click - not a double click (this is a TIMERPROC).
9588  *
9589  * PARAMETER(S):
9590  * [I] hwnd : Handle to the listview
9591  * [I] uMsg : WM_TIMER (ignored)
9592  * [I] idEvent : The timer ID interpreted as a pointer to a DELAYED_EDIT_ITEM struct
9593  * [I] dwTimer : The elapsed time (ignored)
9594  *
9595  * RETURN:
9596  *   None.
9597  */
9598 static VOID CALLBACK LISTVIEW_DelayedEditItem(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime)
9599 {
9600     DELAYED_ITEM_EDIT *editItem = (DELAYED_ITEM_EDIT *)idEvent;
9601     LISTVIEW_INFO *infoPtr = (LISTVIEW_INFO *)GetWindowLongPtrW(hwnd, 0);
9602 
9603     KillTimer(hwnd, idEvent);
9604     editItem->fEnabled = FALSE;
9605     /* check if the item is still selected */
9606     if (infoPtr->bFocus && LISTVIEW_GetItemState(infoPtr, editItem->iItem, LVIS_SELECTED))
9607         LISTVIEW_EditLabelT(infoPtr, editItem->iItem, TRUE);
9608 }
9609 
9610 /***
9611  * DESCRIPTION:
9612  * Creates the listview control - the WM_NCCREATE phase.
9613  *
9614  * PARAMETER(S):
9615  * [I] hwnd : window handle
9616  * [I] lpcs : the create parameters
9617  *
9618  * RETURN:
9619  *   Success: TRUE
9620  *   Failure: FALSE
9621  */
9622 static LRESULT LISTVIEW_NCCreate(HWND hwnd, WPARAM wParam, const CREATESTRUCTW *lpcs)
9623 {
9624   LISTVIEW_INFO *infoPtr;
9625   LOGFONTW logFont;
9626 
9627   TRACE("(lpcs=%p)\n", lpcs);
9628 
9629   /* initialize info pointer */
9630   infoPtr = Alloc(sizeof(LISTVIEW_INFO));
9631   if (!infoPtr) return FALSE;
9632 
9633   SetWindowLongPtrW(hwnd, 0, (DWORD_PTR)infoPtr);
9634 
9635   infoPtr->hwndSelf = hwnd;
9636   infoPtr->dwStyle = lpcs->style;    /* Note: may be changed in WM_CREATE */
9637   map_style_view(infoPtr);
9638   /* determine the type of structures to use */
9639   infoPtr->hwndNotify = lpcs->hwndParent;
9640   /* infoPtr->notifyFormat will be filled in WM_CREATE */
9641 
9642   /* initialize color information  */
9643   infoPtr->clrBk = CLR_NONE;
9644   infoPtr->clrText = CLR_DEFAULT;
9645   infoPtr->clrTextBk = CLR_DEFAULT;
9646   LISTVIEW_SetBkColor(infoPtr, comctl32_color.clrWindow);
9647 #ifdef __REACTOS__
9648   infoPtr->bDefaultBkColor = TRUE;
9649 #endif
9650 
9651   /* set default values */
9652   infoPtr->nFocusedItem = -1;
9653   infoPtr->nSelectionMark = -1;
9654   infoPtr->nHotItem = -1;
9655   infoPtr->redraw = TRUE;
9656   infoPtr->bNoItemMetrics = TRUE;
9657   infoPtr->notify_mask = NOTIFY_MASK_UNMASK_ALL;
9658   infoPtr->autoSpacing = TRUE;
9659   infoPtr->iconSpacing.cx = GetSystemMetrics(SM_CXICONSPACING) - GetSystemMetrics(SM_CXICON);
9660   infoPtr->iconSpacing.cy = GetSystemMetrics(SM_CYICONSPACING) - GetSystemMetrics(SM_CYICON);
9661   infoPtr->nEditLabelItem = -1;
9662   infoPtr->nLButtonDownItem = -1;
9663   infoPtr->dwHoverTime = HOVER_DEFAULT; /* default system hover time */
9664   infoPtr->cWheelRemainder = 0;
9665   infoPtr->nMeasureItemHeight = 0;
9666   infoPtr->xTrackLine = -1;  /* no track line */
9667   infoPtr->itemEdit.fEnabled = FALSE;
9668   infoPtr->iVersion = COMCTL32_VERSION;
9669   infoPtr->colRectsDirty = FALSE;
9670 
9671   /* get default font (icon title) */
9672   SystemParametersInfoW(SPI_GETICONTITLELOGFONT, 0, &logFont, 0);
9673   infoPtr->hDefaultFont = CreateFontIndirectW(&logFont);
9674   infoPtr->hFont = infoPtr->hDefaultFont;
9675   LISTVIEW_SaveTextMetrics(infoPtr);
9676 
9677   /* allocate memory for the data structure */
9678   if (!(infoPtr->selectionRanges = ranges_create(10))) goto fail;
9679   if (!(infoPtr->hdpaItems = DPA_Create(10))) goto fail;
9680   if (!(infoPtr->hdpaItemIds = DPA_Create(10))) goto fail;
9681   if (!(infoPtr->hdpaPosX  = DPA_Create(10))) goto fail;
9682   if (!(infoPtr->hdpaPosY  = DPA_Create(10))) goto fail;
9683   if (!(infoPtr->hdpaColumns = DPA_Create(10))) goto fail;
9684 
9685   return DefWindowProcW(hwnd, WM_NCCREATE, wParam, (LPARAM)lpcs);
9686 
9687 fail:
9688     DestroyWindow(infoPtr->hwndHeader);
9689     ranges_destroy(infoPtr->selectionRanges);
9690     DPA_Destroy(infoPtr->hdpaItems);
9691     DPA_Destroy(infoPtr->hdpaItemIds);
9692     DPA_Destroy(infoPtr->hdpaPosX);
9693     DPA_Destroy(infoPtr->hdpaPosY);
9694     DPA_Destroy(infoPtr->hdpaColumns);
9695     Free(infoPtr);
9696     return FALSE;
9697 }
9698 
9699 /***
9700  * DESCRIPTION:
9701  * Creates the listview control - the WM_CREATE phase. Most of the data is
9702  * already set up in LISTVIEW_NCCreate
9703  *
9704  * PARAMETER(S):
9705  * [I] hwnd : window handle
9706  * [I] lpcs : the create parameters
9707  *
9708  * RETURN:
9709  *   Success: 0
9710  *   Failure: -1
9711  */
9712 static LRESULT LISTVIEW_Create(HWND hwnd, const CREATESTRUCTW *lpcs)
9713 {
9714   LISTVIEW_INFO *infoPtr = (LISTVIEW_INFO *)GetWindowLongPtrW(hwnd, 0);
9715 
9716   TRACE("(lpcs=%p, style=0x%08x)\n", lpcs, lpcs->style);
9717 
9718   infoPtr->dwStyle = lpcs->style;
9719   map_style_view(infoPtr);
9720 
9721   infoPtr->notifyFormat = SendMessageW(infoPtr->hwndNotify, WM_NOTIFYFORMAT,
9722                                        (WPARAM)infoPtr->hwndSelf, NF_QUERY);
9723   /* on error defaulting to ANSI notifications */
9724   if (infoPtr->notifyFormat == 0) infoPtr->notifyFormat = NFR_ANSI;
9725   TRACE("notify format=%d\n", infoPtr->notifyFormat);
9726 
9727   if ((infoPtr->uView == LV_VIEW_DETAILS) && (lpcs->style & WS_VISIBLE))
9728   {
9729     if (LISTVIEW_CreateHeader(infoPtr) < 0)  return -1;
9730   }
9731   else
9732     infoPtr->hwndHeader = 0;
9733 
9734   /* init item size to avoid division by 0 */
9735   LISTVIEW_UpdateItemSize (infoPtr);
9736   LISTVIEW_UpdateSize (infoPtr);
9737 
9738   if (infoPtr->uView == LV_VIEW_DETAILS)
9739   {
9740     if (!(LVS_NOCOLUMNHEADER & lpcs->style) && (WS_VISIBLE & lpcs->style))
9741     {
9742       ShowWindow(infoPtr->hwndHeader, SW_SHOWNORMAL);
9743     }
9744     LISTVIEW_UpdateScroll(infoPtr);
9745     /* send WM_MEASUREITEM notification */
9746     if (infoPtr->dwStyle & LVS_OWNERDRAWFIXED) notify_measureitem(infoPtr);
9747   }
9748 
9749   OpenThemeData(hwnd, themeClass);
9750 
9751   /* initialize the icon sizes */
9752   set_icon_size(&infoPtr->iconSize, infoPtr->himlNormal, infoPtr->uView != LV_VIEW_ICON);
9753   set_icon_size(&infoPtr->iconStateSize, infoPtr->himlState, TRUE);
9754   return 0;
9755 }
9756 
9757 /***
9758  * DESCRIPTION:
9759  * Destroys the listview control.
9760  *
9761  * PARAMETER(S):
9762  * [I] infoPtr : valid pointer to the listview structure
9763  *
9764  * RETURN:
9765  *   Success: 0
9766  *   Failure: -1
9767  */
9768 static LRESULT LISTVIEW_Destroy(LISTVIEW_INFO *infoPtr)
9769 {
9770     HTHEME theme = GetWindowTheme(infoPtr->hwndSelf);
9771     CloseThemeData(theme);
9772 
9773     /* delete all items */
9774     LISTVIEW_DeleteAllItems(infoPtr, TRUE);
9775 
9776     return 0;
9777 }
9778 
9779 /***
9780  * DESCRIPTION:
9781  * Enables the listview control.
9782  *
9783  * PARAMETER(S):
9784  * [I] infoPtr : valid pointer to the listview structure
9785  * [I] bEnable : specifies whether to enable or disable the window
9786  *
9787  * RETURN:
9788  *   SUCCESS : TRUE
9789  *   FAILURE : FALSE
9790  */
9791 static BOOL LISTVIEW_Enable(const LISTVIEW_INFO *infoPtr)
9792 {
9793     if (infoPtr->dwStyle & LVS_OWNERDRAWFIXED)
9794         InvalidateRect(infoPtr->hwndSelf, NULL, TRUE);
9795     return TRUE;
9796 }
9797 
9798 /***
9799  * DESCRIPTION:
9800  * Erases the background of the listview control.
9801  *
9802  * PARAMETER(S):
9803  * [I] infoPtr : valid pointer to the listview structure
9804  * [I] hdc : device context handle
9805  *
9806  * RETURN:
9807  *   SUCCESS : TRUE
9808  *   FAILURE : FALSE
9809  */
9810 static inline BOOL LISTVIEW_EraseBkgnd(const LISTVIEW_INFO *infoPtr, HDC hdc)
9811 {
9812     RECT rc;
9813 
9814     TRACE("(hdc=%p)\n", hdc);
9815 
9816     if (!GetClipBox(hdc, &rc)) return FALSE;
9817 
9818     if (infoPtr->clrBk == CLR_NONE)
9819     {
9820         if (infoPtr->dwLvExStyle & LVS_EX_TRANSPARENTBKGND)
9821             return SendMessageW(infoPtr->hwndNotify, WM_PRINTCLIENT,
9822                                 (WPARAM)hdc, PRF_ERASEBKGND);
9823         else
9824             return SendMessageW(infoPtr->hwndNotify, WM_ERASEBKGND, (WPARAM)hdc, 0);
9825     }
9826 
9827     /* for double buffered controls we need to do this during refresh */
9828     if (infoPtr->dwLvExStyle & LVS_EX_DOUBLEBUFFER) return FALSE;
9829 
9830     return LISTVIEW_FillBkgnd(infoPtr, hdc, &rc);
9831 }
9832 
9833 
9834 /***
9835  * DESCRIPTION:
9836  * Helper function for LISTVIEW_[HV]Scroll *only*.
9837  * Performs vertical/horizontal scrolling by a give amount.
9838  *
9839  * PARAMETER(S):
9840  * [I] infoPtr : valid pointer to the listview structure
9841  * [I] dx : amount of horizontal scroll
9842  * [I] dy : amount of vertical scroll
9843  */
9844 static void scroll_list(LISTVIEW_INFO *infoPtr, INT dx, INT dy)
9845 {
9846     /* now we can scroll the list */
9847     ScrollWindowEx(infoPtr->hwndSelf, dx, dy, &infoPtr->rcList,
9848 		   &infoPtr->rcList, 0, 0, SW_ERASE | SW_INVALIDATE);
9849     /* if we have focus, adjust rect */
9850     OffsetRect(&infoPtr->rcFocus, dx, dy);
9851     UpdateWindow(infoPtr->hwndSelf);
9852 }
9853 
9854 /***
9855  * DESCRIPTION:
9856  * Performs vertical scrolling.
9857  *
9858  * PARAMETER(S):
9859  * [I] infoPtr : valid pointer to the listview structure
9860  * [I] nScrollCode : scroll code
9861  * [I] nScrollDiff : units to scroll in SB_INTERNAL mode, 0 otherwise
9862  * [I] hScrollWnd  : scrollbar control window handle
9863  *
9864  * RETURN:
9865  * Zero
9866  *
9867  * NOTES:
9868  *   SB_LINEUP/SB_LINEDOWN:
9869  *        for LVS_ICON, LVS_SMALLICON is 37 by experiment
9870  *        for LVS_REPORT is 1 line
9871  *        for LVS_LIST cannot occur
9872  *
9873  */
9874 static LRESULT LISTVIEW_VScroll(LISTVIEW_INFO *infoPtr, INT nScrollCode,
9875 				INT nScrollDiff)
9876 {
9877     INT nOldScrollPos, nNewScrollPos;
9878     SCROLLINFO scrollInfo;
9879     BOOL is_an_icon;
9880 
9881     TRACE("(nScrollCode=%d(%s), nScrollDiff=%d)\n", nScrollCode,
9882 	debugscrollcode(nScrollCode), nScrollDiff);
9883 
9884     if (infoPtr->hwndEdit) SendMessageW(infoPtr->hwndEdit, WM_KILLFOCUS, 0, 0);
9885 
9886     scrollInfo.cbSize = sizeof(SCROLLINFO);
9887     scrollInfo.fMask = SIF_PAGE | SIF_POS | SIF_RANGE | SIF_TRACKPOS;
9888 
9889     is_an_icon = ((infoPtr->uView == LV_VIEW_ICON) || (infoPtr->uView == LV_VIEW_SMALLICON));
9890 
9891     if (!GetScrollInfo(infoPtr->hwndSelf, SB_VERT, &scrollInfo)) return 1;
9892 
9893     nOldScrollPos = scrollInfo.nPos;
9894     switch (nScrollCode)
9895     {
9896     case SB_INTERNAL:
9897         break;
9898 
9899     case SB_LINEUP:
9900 	nScrollDiff = (is_an_icon) ? -LISTVIEW_SCROLL_ICON_LINE_SIZE : -1;
9901         break;
9902 
9903     case SB_LINEDOWN:
9904 	nScrollDiff = (is_an_icon) ? LISTVIEW_SCROLL_ICON_LINE_SIZE : 1;
9905         break;
9906 
9907     case SB_PAGEUP:
9908 	nScrollDiff = -scrollInfo.nPage;
9909         break;
9910 
9911     case SB_PAGEDOWN:
9912 	nScrollDiff = scrollInfo.nPage;
9913         break;
9914 
9915     case SB_THUMBPOSITION:
9916     case SB_THUMBTRACK:
9917 	nScrollDiff = scrollInfo.nTrackPos - scrollInfo.nPos;
9918         break;
9919 
9920     default:
9921 	nScrollDiff = 0;
9922     }
9923 
9924     /* quit right away if pos isn't changing */
9925     if (nScrollDiff == 0) return 0;
9926 
9927     /* calculate new position, and handle overflows */
9928     nNewScrollPos = scrollInfo.nPos + nScrollDiff;
9929     if (nScrollDiff > 0) {
9930 	if (nNewScrollPos < nOldScrollPos ||
9931 	    nNewScrollPos > scrollInfo.nMax)
9932 	    nNewScrollPos = scrollInfo.nMax;
9933     } else {
9934 	if (nNewScrollPos > nOldScrollPos ||
9935 	    nNewScrollPos < scrollInfo.nMin)
9936 	    nNewScrollPos = scrollInfo.nMin;
9937     }
9938 
9939     /* set the new position, and reread in case it changed */
9940     scrollInfo.fMask = SIF_POS;
9941     scrollInfo.nPos = nNewScrollPos;
9942     nNewScrollPos = SetScrollInfo(infoPtr->hwndSelf, SB_VERT, &scrollInfo, TRUE);
9943 
9944     /* carry on only if it really changed */
9945     if (nNewScrollPos == nOldScrollPos) return 0;
9946 
9947     /* now adjust to client coordinates */
9948     nScrollDiff = nOldScrollPos - nNewScrollPos;
9949     if (infoPtr->uView == LV_VIEW_DETAILS) nScrollDiff *= infoPtr->nItemHeight;
9950 
9951     /* and scroll the window */
9952     scroll_list(infoPtr, 0, nScrollDiff);
9953 
9954     return 0;
9955 }
9956 
9957 /***
9958  * DESCRIPTION:
9959  * Performs horizontal scrolling.
9960  *
9961  * PARAMETER(S):
9962  * [I] infoPtr : valid pointer to the listview structure
9963  * [I] nScrollCode : scroll code
9964  * [I] nScrollDiff : units to scroll in SB_INTERNAL mode, 0 otherwise
9965  * [I] hScrollWnd  : scrollbar control window handle
9966  *
9967  * RETURN:
9968  * Zero
9969  *
9970  * NOTES:
9971  *   SB_LINELEFT/SB_LINERIGHT:
9972  *        for LVS_ICON, LVS_SMALLICON  1 pixel
9973  *        for LVS_REPORT is 1 pixel
9974  *        for LVS_LIST  is 1 column --> which is a 1 because the
9975  *                                      scroll is based on columns not pixels
9976  *
9977  */
9978 static LRESULT LISTVIEW_HScroll(LISTVIEW_INFO *infoPtr, INT nScrollCode,
9979                                 INT nScrollDiff)
9980 {
9981     INT nOldScrollPos, nNewScrollPos;
9982     SCROLLINFO scrollInfo;
9983     BOOL is_an_icon;
9984 
9985     TRACE("(nScrollCode=%d(%s), nScrollDiff=%d)\n", nScrollCode,
9986 	debugscrollcode(nScrollCode), nScrollDiff);
9987 
9988     if (infoPtr->hwndEdit) SendMessageW(infoPtr->hwndEdit, WM_KILLFOCUS, 0, 0);
9989 
9990     scrollInfo.cbSize = sizeof(SCROLLINFO);
9991     scrollInfo.fMask = SIF_PAGE | SIF_POS | SIF_RANGE | SIF_TRACKPOS;
9992 
9993     is_an_icon = ((infoPtr->uView == LV_VIEW_ICON) || (infoPtr->uView == LV_VIEW_SMALLICON));
9994 
9995     if (!GetScrollInfo(infoPtr->hwndSelf, SB_HORZ, &scrollInfo)) return 1;
9996 
9997     nOldScrollPos = scrollInfo.nPos;
9998 
9999     switch (nScrollCode)
10000     {
10001     case SB_INTERNAL:
10002         break;
10003 
10004     case SB_LINELEFT:
10005 	nScrollDiff = (is_an_icon) ? -LISTVIEW_SCROLL_ICON_LINE_SIZE : -1;
10006         break;
10007 
10008     case SB_LINERIGHT:
10009 	nScrollDiff = (is_an_icon) ? LISTVIEW_SCROLL_ICON_LINE_SIZE : 1;
10010         break;
10011 
10012     case SB_PAGELEFT:
10013 	nScrollDiff = -scrollInfo.nPage;
10014         break;
10015 
10016     case SB_PAGERIGHT:
10017 	nScrollDiff = scrollInfo.nPage;
10018         break;
10019 
10020     case SB_THUMBPOSITION:
10021     case SB_THUMBTRACK:
10022 	nScrollDiff = scrollInfo.nTrackPos - scrollInfo.nPos;
10023 	break;
10024 
10025     default:
10026 	nScrollDiff = 0;
10027     }
10028 
10029     /* quit right away if pos isn't changing */
10030     if (nScrollDiff == 0) return 0;
10031 
10032     /* calculate new position, and handle overflows */
10033     nNewScrollPos = scrollInfo.nPos + nScrollDiff;
10034     if (nScrollDiff > 0) {
10035 	if (nNewScrollPos < nOldScrollPos ||
10036 	    nNewScrollPos > scrollInfo.nMax)
10037 	    nNewScrollPos = scrollInfo.nMax;
10038     } else {
10039 	if (nNewScrollPos > nOldScrollPos ||
10040 	    nNewScrollPos < scrollInfo.nMin)
10041 	    nNewScrollPos = scrollInfo.nMin;
10042     }
10043 
10044     /* set the new position, and reread in case it changed */
10045     scrollInfo.fMask = SIF_POS;
10046     scrollInfo.nPos = nNewScrollPos;
10047     nNewScrollPos = SetScrollInfo(infoPtr->hwndSelf, SB_HORZ, &scrollInfo, TRUE);
10048 
10049     /* carry on only if it really changed */
10050     if (nNewScrollPos == nOldScrollPos) return 0;
10051 
10052     LISTVIEW_UpdateHeaderSize(infoPtr, nNewScrollPos);
10053 
10054     /* now adjust to client coordinates */
10055     nScrollDiff = nOldScrollPos - nNewScrollPos;
10056     if (infoPtr->uView == LV_VIEW_LIST) nScrollDiff *= infoPtr->nItemWidth;
10057 
10058     /* and scroll the window */
10059     scroll_list(infoPtr, nScrollDiff, 0);
10060 
10061     return 0;
10062 }
10063 
10064 static LRESULT LISTVIEW_MouseWheel(LISTVIEW_INFO *infoPtr, INT wheelDelta)
10065 {
10066     INT pulScrollLines = 3;
10067 
10068     TRACE("(wheelDelta=%d)\n", wheelDelta);
10069 
10070     switch(infoPtr->uView)
10071     {
10072     case LV_VIEW_ICON:
10073     case LV_VIEW_SMALLICON:
10074        /*
10075         *  listview should be scrolled by a multiple of 37 dependently on its dimension or its visible item number
10076         *  should be fixed in the future.
10077         */
10078         LISTVIEW_VScroll(infoPtr, SB_INTERNAL, (wheelDelta > 0) ?
10079                 -LISTVIEW_SCROLL_ICON_LINE_SIZE : LISTVIEW_SCROLL_ICON_LINE_SIZE);
10080         break;
10081 
10082     case LV_VIEW_DETAILS:
10083         SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
10084 
10085         /* if scrolling changes direction, ignore left overs */
10086         if ((wheelDelta < 0 && infoPtr->cWheelRemainder < 0) ||
10087             (wheelDelta > 0 && infoPtr->cWheelRemainder > 0))
10088             infoPtr->cWheelRemainder += wheelDelta;
10089         else
10090             infoPtr->cWheelRemainder = wheelDelta;
10091         if (infoPtr->cWheelRemainder && pulScrollLines)
10092         {
10093             int cLineScroll;
10094             pulScrollLines = min((UINT)LISTVIEW_GetCountPerColumn(infoPtr), pulScrollLines);
10095             cLineScroll = pulScrollLines * infoPtr->cWheelRemainder / WHEEL_DELTA;
10096             infoPtr->cWheelRemainder -= WHEEL_DELTA * cLineScroll / pulScrollLines;
10097             LISTVIEW_VScroll(infoPtr, SB_INTERNAL, -cLineScroll);
10098         }
10099         break;
10100 
10101     case LV_VIEW_LIST:
10102         LISTVIEW_HScroll(infoPtr, (wheelDelta > 0) ? SB_LINELEFT : SB_LINERIGHT, 0);
10103         break;
10104     }
10105     return 0;
10106 }
10107 
10108 /***
10109  * DESCRIPTION:
10110  * ???
10111  *
10112  * PARAMETER(S):
10113  * [I] infoPtr : valid pointer to the listview structure
10114  * [I] nVirtualKey : virtual key
10115  * [I] lKeyData : key data
10116  *
10117  * RETURN:
10118  * Zero
10119  */
10120 static LRESULT LISTVIEW_KeyDown(LISTVIEW_INFO *infoPtr, INT nVirtualKey, LONG lKeyData)
10121 {
10122   HWND hwndSelf = infoPtr->hwndSelf;
10123   INT nItem = -1;
10124   NMLVKEYDOWN nmKeyDown;
10125 
10126   TRACE("(nVirtualKey=%d, lKeyData=%d)\n", nVirtualKey, lKeyData);
10127 
10128   /* send LVN_KEYDOWN notification */
10129   nmKeyDown.wVKey = nVirtualKey;
10130   nmKeyDown.flags = 0;
10131   notify_hdr(infoPtr, LVN_KEYDOWN, &nmKeyDown.hdr);
10132   if (!IsWindow(hwndSelf))
10133     return 0;
10134 
10135   switch (nVirtualKey)
10136   {
10137   case VK_SPACE:
10138     nItem = infoPtr->nFocusedItem;
10139     if (infoPtr->dwLvExStyle & LVS_EX_CHECKBOXES)
10140         toggle_checkbox_state(infoPtr, infoPtr->nFocusedItem);
10141     break;
10142 
10143   case VK_RETURN:
10144     if ((infoPtr->nItemCount > 0) && (infoPtr->nFocusedItem != -1))
10145     {
10146         if (!notify(infoPtr, NM_RETURN)) return 0;
10147         if (!notify(infoPtr, LVN_ITEMACTIVATE)) return 0;
10148     }
10149     break;
10150 
10151   case VK_HOME:
10152     if (infoPtr->nItemCount > 0)
10153       nItem = 0;
10154     break;
10155 
10156   case VK_END:
10157     if (infoPtr->nItemCount > 0)
10158       nItem = infoPtr->nItemCount - 1;
10159     break;
10160 
10161   case VK_LEFT:
10162     nItem = LISTVIEW_GetNextItem(infoPtr, infoPtr->nFocusedItem, LVNI_TOLEFT);
10163     break;
10164 
10165   case VK_UP:
10166     nItem = LISTVIEW_GetNextItem(infoPtr, infoPtr->nFocusedItem, LVNI_ABOVE);
10167     break;
10168 
10169   case VK_RIGHT:
10170     nItem = LISTVIEW_GetNextItem(infoPtr, infoPtr->nFocusedItem, LVNI_TORIGHT);
10171     break;
10172 
10173   case VK_DOWN:
10174     nItem = LISTVIEW_GetNextItem(infoPtr, infoPtr->nFocusedItem, LVNI_BELOW);
10175     break;
10176 
10177   case VK_PRIOR:
10178     if (infoPtr->uView == LV_VIEW_DETAILS)
10179     {
10180       INT topidx = LISTVIEW_GetTopIndex(infoPtr);
10181       if (infoPtr->nFocusedItem == topidx)
10182         nItem = topidx - LISTVIEW_GetCountPerColumn(infoPtr) + 1;
10183       else
10184         nItem = topidx;
10185     }
10186     else
10187       nItem = infoPtr->nFocusedItem - LISTVIEW_GetCountPerColumn(infoPtr)
10188                                     * LISTVIEW_GetCountPerRow(infoPtr);
10189     if(nItem < 0) nItem = 0;
10190     break;
10191 
10192   case VK_NEXT:
10193     if (infoPtr->uView == LV_VIEW_DETAILS)
10194     {
10195       INT topidx = LISTVIEW_GetTopIndex(infoPtr);
10196       INT cnt = LISTVIEW_GetCountPerColumn(infoPtr);
10197       if (infoPtr->nFocusedItem == topidx + cnt - 1)
10198         nItem = infoPtr->nFocusedItem + cnt - 1;
10199       else
10200         nItem = topidx + cnt - 1;
10201     }
10202     else
10203       nItem = infoPtr->nFocusedItem + LISTVIEW_GetCountPerColumn(infoPtr)
10204                                     * LISTVIEW_GetCountPerRow(infoPtr);
10205     if(nItem >= infoPtr->nItemCount) nItem = infoPtr->nItemCount - 1;
10206     break;
10207   }
10208 
10209   if ((nItem != -1) && (nItem != infoPtr->nFocusedItem || nVirtualKey == VK_SPACE))
10210       LISTVIEW_KeySelection(infoPtr, nItem, nVirtualKey == VK_SPACE);
10211 
10212   return 0;
10213 }
10214 
10215 /***
10216  * DESCRIPTION:
10217  * Kills the focus.
10218  *
10219  * PARAMETER(S):
10220  * [I] infoPtr : valid pointer to the listview structure
10221  *
10222  * RETURN:
10223  * Zero
10224  */
10225 static LRESULT LISTVIEW_KillFocus(LISTVIEW_INFO *infoPtr)
10226 {
10227     TRACE("()\n");
10228 
10229     /* drop any left over scroll amount */
10230     infoPtr->cWheelRemainder = 0;
10231 
10232     /* if we did not have the focus, there's nothing more to do */
10233     if (!infoPtr->bFocus) return 0;
10234 
10235     /* send NM_KILLFOCUS notification */
10236     if (!notify(infoPtr, NM_KILLFOCUS)) return 0;
10237 
10238     /* if we have a focus rectangle, get rid of it */
10239     LISTVIEW_ShowFocusRect(infoPtr, FALSE);
10240 
10241     /* if have a marquee selection, stop it */
10242     if (infoPtr->bMarqueeSelect)
10243     {
10244         /* Remove the marquee rectangle and release our mouse capture */
10245         LISTVIEW_InvalidateRect(infoPtr, &infoPtr->marqueeRect);
10246         ReleaseCapture();
10247 
10248         SetRectEmpty(&infoPtr->marqueeRect);
10249 
10250         infoPtr->bMarqueeSelect = FALSE;
10251         infoPtr->bScrolling = FALSE;
10252         KillTimer(infoPtr->hwndSelf, (UINT_PTR) infoPtr);
10253     }
10254 
10255     /* set window focus flag */
10256     infoPtr->bFocus = FALSE;
10257 
10258     /* invalidate the selected items before resetting focus flag */
10259     LISTVIEW_InvalidateSelectedItems(infoPtr);
10260 
10261     return 0;
10262 }
10263 
10264 /***
10265  * DESCRIPTION:
10266  * Processes double click messages (left mouse button).
10267  *
10268  * PARAMETER(S):
10269  * [I] infoPtr : valid pointer to the listview structure
10270  * [I] wKey : key flag
10271  * [I] x,y : mouse coordinate
10272  *
10273  * RETURN:
10274  * Zero
10275  */
10276 static LRESULT LISTVIEW_LButtonDblClk(LISTVIEW_INFO *infoPtr, WORD wKey, INT x, INT y)
10277 {
10278     LVHITTESTINFO htInfo;
10279 
10280     TRACE("(key=%hu, X=%u, Y=%u)\n", wKey, x, y);
10281 
10282     /* Cancel the item edition if any */
10283     if (infoPtr->itemEdit.fEnabled)
10284     {
10285       KillTimer(infoPtr->hwndSelf, (UINT_PTR)&infoPtr->itemEdit);
10286       infoPtr->itemEdit.fEnabled = FALSE;
10287     }
10288 
10289     /* send NM_RELEASEDCAPTURE notification */
10290     if (!notify(infoPtr, NM_RELEASEDCAPTURE)) return 0;
10291 
10292     htInfo.pt.x = x;
10293     htInfo.pt.y = y;
10294 
10295     /* send NM_DBLCLK notification */
10296     LISTVIEW_HitTest(infoPtr, &htInfo, TRUE, FALSE);
10297     if (!notify_click(infoPtr, NM_DBLCLK, &htInfo)) return 0;
10298 
10299     /* To send the LVN_ITEMACTIVATE, it must be on an Item */
10300     if(htInfo.iItem != -1) notify_itemactivate(infoPtr,&htInfo);
10301 
10302     return 0;
10303 }
10304 
10305 static LRESULT LISTVIEW_TrackMouse(const LISTVIEW_INFO *infoPtr, POINT pt)
10306 {
10307     MSG msg;
10308     RECT r;
10309 
10310     r.top = r.bottom = pt.y;
10311     r.left = r.right = pt.x;
10312 
10313     InflateRect(&r, GetSystemMetrics(SM_CXDRAG), GetSystemMetrics(SM_CYDRAG));
10314 
10315     SetCapture(infoPtr->hwndSelf);
10316 
10317     while (1)
10318     {
10319 	if (PeekMessageW(&msg, 0, 0, 0, PM_REMOVE | PM_NOYIELD))
10320 	{
10321 	    if (msg.message == WM_MOUSEMOVE)
10322 	    {
10323 		pt.x = (short)LOWORD(msg.lParam);
10324 		pt.y = (short)HIWORD(msg.lParam);
10325 		if (PtInRect(&r, pt))
10326 		    continue;
10327 		else
10328 		{
10329 		    ReleaseCapture();
10330 		    return 1;
10331 		}
10332 	    }
10333 	    else if (msg.message >= WM_LBUTTONDOWN &&
10334 		     msg.message <= WM_RBUTTONDBLCLK)
10335 	    {
10336 		break;
10337 	    }
10338 
10339 	    DispatchMessageW(&msg);
10340 	}
10341 
10342 	if (GetCapture() != infoPtr->hwndSelf)
10343 	    return 0;
10344     }
10345 
10346     ReleaseCapture();
10347     return 0;
10348 }
10349 
10350 
10351 /***
10352  * DESCRIPTION:
10353  * Processes mouse down messages (left mouse button).
10354  *
10355  * PARAMETERS:
10356  *   infoPtr  [I ] valid pointer to the listview structure
10357  *   wKey     [I ] key flag
10358  *   x,y      [I ] mouse coordinate
10359  *
10360  * RETURN:
10361  *   Zero
10362  */
10363 static LRESULT LISTVIEW_LButtonDown(LISTVIEW_INFO *infoPtr, WORD wKey, INT x, INT y)
10364 {
10365   LVHITTESTINFO lvHitTestInfo;
10366   static BOOL bGroupSelect = TRUE;
10367   POINT pt = { x, y };
10368   INT nItem;
10369 
10370   TRACE("(key=%hu, X=%u, Y=%u)\n", wKey, x, y);
10371 
10372   /* send NM_RELEASEDCAPTURE notification */
10373   if (!notify(infoPtr, NM_RELEASEDCAPTURE)) return 0;
10374 
10375   /* set left button down flag and record the click position */
10376   infoPtr->bLButtonDown = TRUE;
10377   infoPtr->ptClickPos = pt;
10378   infoPtr->bDragging = FALSE;
10379   infoPtr->bMarqueeSelect = FALSE;
10380   infoPtr->bScrolling = FALSE;
10381 
10382   lvHitTestInfo.pt.x = x;
10383   lvHitTestInfo.pt.y = y;
10384 
10385   nItem = LISTVIEW_HitTest(infoPtr, &lvHitTestInfo, TRUE, TRUE);
10386   TRACE("at %s, nItem=%d\n", wine_dbgstr_point(&pt), nItem);
10387   if ((nItem >= 0) && (nItem < infoPtr->nItemCount))
10388   {
10389     if ((infoPtr->dwLvExStyle & LVS_EX_CHECKBOXES) && (lvHitTestInfo.flags & LVHT_ONITEMSTATEICON))
10390     {
10391         notify_click(infoPtr, NM_CLICK, &lvHitTestInfo);
10392         toggle_checkbox_state(infoPtr, nItem);
10393         infoPtr->bLButtonDown = FALSE;
10394         return 0;
10395     }
10396 
10397     if (infoPtr->dwStyle & LVS_SINGLESEL)
10398     {
10399       if (LISTVIEW_GetItemState(infoPtr, nItem, LVIS_SELECTED))
10400         infoPtr->nEditLabelItem = nItem;
10401       else
10402         LISTVIEW_SetSelection(infoPtr, nItem);
10403     }
10404     else
10405     {
10406       if ((wKey & MK_CONTROL) && (wKey & MK_SHIFT))
10407       {
10408         if (bGroupSelect)
10409 	{
10410           if (!LISTVIEW_AddGroupSelection(infoPtr, nItem)) return 0;
10411     	  LISTVIEW_SetItemFocus(infoPtr, nItem);
10412           infoPtr->nSelectionMark = nItem;
10413 	}
10414         else
10415 	{
10416           LVITEMW item;
10417 
10418 	  item.state = LVIS_SELECTED | LVIS_FOCUSED;
10419 	  item.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
10420 
10421 	  LISTVIEW_SetItemState(infoPtr,nItem,&item);
10422 	  infoPtr->nSelectionMark = nItem;
10423 	}
10424       }
10425       else if (wKey & MK_CONTROL)
10426       {
10427         LVITEMW item;
10428 
10429 	bGroupSelect = (LISTVIEW_GetItemState(infoPtr, nItem, LVIS_SELECTED) == 0);
10430 
10431 	item.state = (bGroupSelect ? LVIS_SELECTED : 0) | LVIS_FOCUSED;
10432         item.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
10433 	LISTVIEW_SetItemState(infoPtr, nItem, &item);
10434         infoPtr->nSelectionMark = nItem;
10435       }
10436       else  if (wKey & MK_SHIFT)
10437       {
10438         LISTVIEW_SetGroupSelection(infoPtr, nItem);
10439       }
10440       else
10441       {
10442 	if (LISTVIEW_GetItemState(infoPtr, nItem, LVIS_SELECTED))
10443 	{
10444 	  infoPtr->nEditLabelItem = nItem;
10445 	  infoPtr->nLButtonDownItem = nItem;
10446 
10447           LISTVIEW_SetItemFocus(infoPtr, nItem);
10448 	}
10449 	else
10450 	  /* set selection (clears other pre-existing selections) */
10451 	  LISTVIEW_SetSelection(infoPtr, nItem);
10452       }
10453     }
10454 
10455     if (!infoPtr->bFocus)
10456         SetFocus(infoPtr->hwndSelf);
10457 
10458     if (infoPtr->dwLvExStyle & LVS_EX_ONECLICKACTIVATE)
10459         if(lvHitTestInfo.iItem != -1) notify_itemactivate(infoPtr,&lvHitTestInfo);
10460   }
10461   else
10462   {
10463     if (!infoPtr->bFocus)
10464         SetFocus(infoPtr->hwndSelf);
10465 
10466     /* remove all selections */
10467     if (!(wKey & MK_CONTROL) && !(wKey & MK_SHIFT))
10468         LISTVIEW_DeselectAll(infoPtr);
10469     ReleaseCapture();
10470   }
10471 
10472   return 0;
10473 }
10474 
10475 /***
10476  * DESCRIPTION:
10477  * Processes mouse up messages (left mouse button).
10478  *
10479  * PARAMETERS:
10480  *   infoPtr [I ] valid pointer to the listview structure
10481  *   wKey    [I ] key flag
10482  *   x,y     [I ] mouse coordinate
10483  *
10484  * RETURN:
10485  *   Zero
10486  */
10487 static LRESULT LISTVIEW_LButtonUp(LISTVIEW_INFO *infoPtr, WORD wKey, INT x, INT y)
10488 {
10489     LVHITTESTINFO lvHitTestInfo;
10490 
10491     TRACE("(key=%hu, X=%u, Y=%u)\n", wKey, x, y);
10492 
10493     if (!infoPtr->bLButtonDown) return 0;
10494 
10495     lvHitTestInfo.pt.x = x;
10496     lvHitTestInfo.pt.y = y;
10497 
10498     /* send NM_CLICK notification */
10499     LISTVIEW_HitTest(infoPtr, &lvHitTestInfo, TRUE, FALSE);
10500     if (!notify_click(infoPtr, NM_CLICK, &lvHitTestInfo)) return 0;
10501 
10502     /* set left button flag */
10503     infoPtr->bLButtonDown = FALSE;
10504 
10505     /* set a single selection, reset others */
10506     if(lvHitTestInfo.iItem == infoPtr->nLButtonDownItem && lvHitTestInfo.iItem != -1)
10507         LISTVIEW_SetSelection(infoPtr, infoPtr->nLButtonDownItem);
10508     infoPtr->nLButtonDownItem = -1;
10509 
10510     if (infoPtr->bDragging || infoPtr->bMarqueeSelect)
10511     {
10512         /* Remove the marquee rectangle and release our mouse capture */
10513         if (infoPtr->bMarqueeSelect)
10514         {
10515             LISTVIEW_InvalidateRect(infoPtr, &infoPtr->marqueeDrawRect);
10516             ReleaseCapture();
10517         }
10518 
10519         SetRectEmpty(&infoPtr->marqueeRect);
10520         SetRectEmpty(&infoPtr->marqueeDrawRect);
10521 
10522         infoPtr->bDragging = FALSE;
10523         infoPtr->bMarqueeSelect = FALSE;
10524         infoPtr->bScrolling = FALSE;
10525 
10526         KillTimer(infoPtr->hwndSelf, (UINT_PTR) infoPtr);
10527         return 0;
10528     }
10529 
10530     /* if we clicked on a selected item, edit the label */
10531     if(lvHitTestInfo.iItem == infoPtr->nEditLabelItem && (lvHitTestInfo.flags & LVHT_ONITEMLABEL))
10532     {
10533         /* we want to make sure the user doesn't want to do a double click. So we will
10534          * delay the edit. WM_LBUTTONDBLCLICK will cancel the timer
10535          */
10536         infoPtr->itemEdit.fEnabled = TRUE;
10537         infoPtr->itemEdit.iItem = lvHitTestInfo.iItem;
10538         SetTimer(infoPtr->hwndSelf,
10539             (UINT_PTR)&infoPtr->itemEdit,
10540             GetDoubleClickTime(),
10541             LISTVIEW_DelayedEditItem);
10542     }
10543 
10544     return 0;
10545 }
10546 
10547 /***
10548  * DESCRIPTION:
10549  * Destroys the listview control (called after WM_DESTROY).
10550  *
10551  * PARAMETER(S):
10552  * [I] infoPtr : valid pointer to the listview structure
10553  *
10554  * RETURN:
10555  * Zero
10556  */
10557 static LRESULT LISTVIEW_NCDestroy(LISTVIEW_INFO *infoPtr)
10558 {
10559   INT i;
10560 
10561   TRACE("()\n");
10562 
10563   /* destroy data structure */
10564   DPA_Destroy(infoPtr->hdpaItems);
10565   DPA_Destroy(infoPtr->hdpaItemIds);
10566   DPA_Destroy(infoPtr->hdpaPosX);
10567   DPA_Destroy(infoPtr->hdpaPosY);
10568   /* columns */
10569   for (i = 0; i < DPA_GetPtrCount(infoPtr->hdpaColumns); i++)
10570       Free(DPA_GetPtr(infoPtr->hdpaColumns, i));
10571   DPA_Destroy(infoPtr->hdpaColumns);
10572   ranges_destroy(infoPtr->selectionRanges);
10573 
10574   /* destroy image lists */
10575   if (!(infoPtr->dwStyle & LVS_SHAREIMAGELISTS))
10576   {
10577       ImageList_Destroy(infoPtr->himlNormal);
10578       ImageList_Destroy(infoPtr->himlSmall);
10579       ImageList_Destroy(infoPtr->himlState);
10580   }
10581 
10582   /* destroy font, bkgnd brush */
10583   infoPtr->hFont = 0;
10584   if (infoPtr->hDefaultFont) DeleteObject(infoPtr->hDefaultFont);
10585   if (infoPtr->clrBk != CLR_NONE) DeleteObject(infoPtr->hBkBrush);
10586 
10587   SetWindowLongPtrW(infoPtr->hwndSelf, 0, 0);
10588 
10589   /* free listview info pointer*/
10590   Free(infoPtr);
10591 
10592   return 0;
10593 }
10594 
10595 /***
10596  * DESCRIPTION:
10597  * Handles notifications.
10598  *
10599  * PARAMETER(S):
10600  * [I] infoPtr : valid pointer to the listview structure
10601  * [I] lpnmhdr : notification information
10602  *
10603  * RETURN:
10604  * Zero
10605  */
10606 static LRESULT LISTVIEW_Notify(LISTVIEW_INFO *infoPtr, NMHDR *lpnmhdr)
10607 {
10608     NMHEADERW *lpnmh;
10609 
10610     TRACE("(lpnmhdr=%p)\n", lpnmhdr);
10611 
10612     if (!lpnmhdr || lpnmhdr->hwndFrom != infoPtr->hwndHeader) return 0;
10613 
10614     /* remember: HDN_LAST < HDN_FIRST */
10615     if (lpnmhdr->code > HDN_FIRST || lpnmhdr->code < HDN_LAST) return 0;
10616     lpnmh = (NMHEADERW *)lpnmhdr;
10617 
10618     if (lpnmh->iItem < 0 || lpnmh->iItem >= DPA_GetPtrCount(infoPtr->hdpaColumns)) return 0;
10619 
10620     switch (lpnmhdr->code)
10621     {
10622 	case HDN_TRACKW:
10623 	case HDN_TRACKA:
10624 	{
10625 	    COLUMN_INFO *lpColumnInfo;
10626 	    POINT ptOrigin;
10627 	    INT x;
10628 
10629 	    if (!lpnmh->pitem || !(lpnmh->pitem->mask & HDI_WIDTH))
10630 		break;
10631 
10632             /* remove the old line (if any) */
10633             LISTVIEW_DrawTrackLine(infoPtr);
10634 
10635             /* compute & draw the new line */
10636             lpColumnInfo = LISTVIEW_GetColumnInfo(infoPtr, lpnmh->iItem);
10637             x = lpColumnInfo->rcHeader.left + lpnmh->pitem->cxy;
10638             LISTVIEW_GetOrigin(infoPtr, &ptOrigin);
10639             infoPtr->xTrackLine = x + ptOrigin.x;
10640             LISTVIEW_DrawTrackLine(infoPtr);
10641             return notify_forward_header(infoPtr, lpnmh);
10642 	}
10643 
10644 	case HDN_ENDTRACKA:
10645 	case HDN_ENDTRACKW:
10646 	    /* remove the track line (if any) */
10647 	    LISTVIEW_DrawTrackLine(infoPtr);
10648 	    infoPtr->xTrackLine = -1;
10649             return notify_forward_header(infoPtr, lpnmh);
10650 
10651         case HDN_BEGINDRAG:
10652             if ((infoPtr->dwLvExStyle & LVS_EX_HEADERDRAGDROP) == 0) return 1;
10653             return notify_forward_header(infoPtr, lpnmh);
10654 
10655         case HDN_ENDDRAG:
10656             infoPtr->colRectsDirty = TRUE;
10657             LISTVIEW_InvalidateList(infoPtr);
10658             return notify_forward_header(infoPtr, lpnmh);
10659 
10660 	case HDN_ITEMCHANGEDW:
10661 	case HDN_ITEMCHANGEDA:
10662 	{
10663 	    COLUMN_INFO *lpColumnInfo;
10664 	    HDITEMW hdi;
10665 	    INT dx, cxy;
10666 
10667 	    if (!lpnmh->pitem || !(lpnmh->pitem->mask & HDI_WIDTH))
10668 	    {
10669 		hdi.mask = HDI_WIDTH;
10670 		if (!SendMessageW(infoPtr->hwndHeader, HDM_GETITEMW, lpnmh->iItem, (LPARAM)&hdi)) return 0;
10671 		cxy = hdi.cxy;
10672 	    }
10673 	    else
10674 		cxy = lpnmh->pitem->cxy;
10675 
10676 	    /* determine how much we change since the last know position */
10677 	    lpColumnInfo = LISTVIEW_GetColumnInfo(infoPtr, lpnmh->iItem);
10678 	    dx = cxy - (lpColumnInfo->rcHeader.right - lpColumnInfo->rcHeader.left);
10679 	    if (dx != 0)
10680 	    {
10681 		lpColumnInfo->rcHeader.right += dx;
10682 
10683 		hdi.mask = HDI_ORDER;
10684 		SendMessageW(infoPtr->hwndHeader, HDM_GETITEMW, lpnmh->iItem, (LPARAM)&hdi);
10685 
10686 		/* not the rightmost one */
10687 		if (hdi.iOrder + 1 < DPA_GetPtrCount(infoPtr->hdpaColumns))
10688 		{
10689 		    INT nIndex = SendMessageW(infoPtr->hwndHeader, HDM_ORDERTOINDEX,
10690 					      hdi.iOrder + 1, 0);
10691 		    LISTVIEW_ScrollColumns(infoPtr, nIndex, dx);
10692 		}
10693 		else
10694 		{
10695 		    /* only needs to update the scrolls */
10696 		    infoPtr->nItemWidth += dx;
10697 		    LISTVIEW_UpdateScroll(infoPtr);
10698 		}
10699 		LISTVIEW_UpdateItemSize(infoPtr);
10700 		if (infoPtr->uView == LV_VIEW_DETAILS && is_redrawing(infoPtr))
10701 		{
10702 		    POINT ptOrigin;
10703 		    RECT rcCol = lpColumnInfo->rcHeader;
10704 
10705 		    LISTVIEW_GetOrigin(infoPtr, &ptOrigin);
10706 		    OffsetRect(&rcCol, ptOrigin.x, 0);
10707 
10708 		    rcCol.top = infoPtr->rcList.top;
10709 		    rcCol.bottom = infoPtr->rcList.bottom;
10710 
10711 		    /* resizing left-aligned columns leaves most of the left side untouched */
10712 		    if ((lpColumnInfo->fmt & LVCFMT_JUSTIFYMASK) == LVCFMT_LEFT)
10713 		    {
10714 			INT nMaxDirty = infoPtr->nEllipsisWidth + infoPtr->ntmMaxCharWidth;
10715 			if (dx > 0)
10716 			    nMaxDirty += dx;
10717 			rcCol.left = max (rcCol.left, rcCol.right - nMaxDirty);
10718 		    }
10719 
10720 		    /* when shrinking the last column clear the now unused field */
10721 		    if (hdi.iOrder == DPA_GetPtrCount(infoPtr->hdpaColumns) - 1)
10722 		    {
10723 		        RECT right;
10724 
10725 		        rcCol.right -= dx;
10726 
10727 		        /* deal with right from rightmost column area */
10728 		        right.left = rcCol.right;
10729 		        right.top  = rcCol.top;
10730 		        right.bottom = rcCol.bottom;
10731 		        right.right = infoPtr->rcList.right;
10732 
10733 		        LISTVIEW_InvalidateRect(infoPtr, &right);
10734 		    }
10735 
10736 		    LISTVIEW_InvalidateRect(infoPtr, &rcCol);
10737 		}
10738 	    }
10739 	    break;
10740         }
10741 
10742 	case HDN_ITEMCLICKW:
10743 	case HDN_ITEMCLICKA:
10744 	{
10745             /* Handle sorting by Header Column */
10746             NMLISTVIEW nmlv;
10747 
10748             ZeroMemory(&nmlv, sizeof(NMLISTVIEW));
10749             nmlv.iItem = -1;
10750             nmlv.iSubItem = lpnmh->iItem;
10751             notify_listview(infoPtr, LVN_COLUMNCLICK, &nmlv);
10752             return notify_forward_header(infoPtr, lpnmh);
10753         }
10754 
10755 	case HDN_DIVIDERDBLCLICKW:
10756 	case HDN_DIVIDERDBLCLICKA:
10757             /* FIXME: for LVS_EX_HEADERINALLVIEWS and not LV_VIEW_DETAILS
10758                       we should use LVSCW_AUTOSIZE_USEHEADER, helper rework or
10759                       split needed for that */
10760             LISTVIEW_SetColumnWidth(infoPtr, lpnmh->iItem, LVSCW_AUTOSIZE);
10761             return notify_forward_header(infoPtr, lpnmh);
10762     }
10763     return 0;
10764 }
10765 
10766 /***
10767  * DESCRIPTION:
10768  * Paint non-client area of control.
10769  *
10770  * PARAMETER(S):
10771  * [I] infoPtr : valid pointer to the listview structureof the sender
10772  * [I] region : update region
10773  *
10774  * RETURN:
10775  *  TRUE  - frame was painted
10776  *  FALSE - call default window proc
10777  */
10778 static BOOL LISTVIEW_NCPaint(const LISTVIEW_INFO *infoPtr, HRGN region)
10779 {
10780     HTHEME theme = GetWindowTheme (infoPtr->hwndSelf);
10781     HDC dc;
10782     RECT r;
10783     HRGN cliprgn;
10784     int cxEdge = GetSystemMetrics (SM_CXEDGE),
10785         cyEdge = GetSystemMetrics (SM_CYEDGE);
10786 
10787     if (!theme)
10788        return DefWindowProcW (infoPtr->hwndSelf, WM_NCPAINT, (WPARAM)region, 0);
10789 
10790     GetWindowRect(infoPtr->hwndSelf, &r);
10791 
10792     cliprgn = CreateRectRgn (r.left + cxEdge, r.top + cyEdge,
10793         r.right - cxEdge, r.bottom - cyEdge);
10794     if (region != (HRGN)1)
10795         CombineRgn (cliprgn, cliprgn, region, RGN_AND);
10796     OffsetRect(&r, -r.left, -r.top);
10797 
10798 #ifdef __REACTOS__ /* r73789 */
10799     dc = GetWindowDC(infoPtr->hwndSelf);
10800     /* Exclude client part */
10801     ExcludeClipRect(dc, r.left + cxEdge, r.top + cyEdge,
10802         r.right - cxEdge, r.bottom -cyEdge);
10803 #else
10804     dc = GetDCEx(infoPtr->hwndSelf, region, DCX_WINDOW|DCX_INTERSECTRGN);
10805     OffsetRect(&r, -r.left, -r.top);
10806 #endif
10807 
10808     if (IsThemeBackgroundPartiallyTransparent (theme, 0, 0))
10809         DrawThemeParentBackground(infoPtr->hwndSelf, dc, &r);
10810     DrawThemeBackground (theme, dc, 0, 0, &r, 0);
10811     ReleaseDC(infoPtr->hwndSelf, dc);
10812 
10813     /* Call default proc to get the scrollbars etc. painted */
10814     DefWindowProcW (infoPtr->hwndSelf, WM_NCPAINT, (WPARAM)cliprgn, 0);
10815 
10816     return FALSE;
10817 }
10818 
10819 /***
10820  * DESCRIPTION:
10821  * Determines the type of structure to use.
10822  *
10823  * PARAMETER(S):
10824  * [I] infoPtr : valid pointer to the listview structureof the sender
10825  * [I] hwndFrom : listview window handle
10826  * [I] nCommand : command specifying the nature of the WM_NOTIFYFORMAT
10827  *
10828  * RETURN:
10829  * Zero
10830  */
10831 static LRESULT LISTVIEW_NotifyFormat(LISTVIEW_INFO *infoPtr, HWND hwndFrom, INT nCommand)
10832 {
10833     TRACE("(hwndFrom=%p, nCommand=%d)\n", hwndFrom, nCommand);
10834 
10835     if (nCommand == NF_REQUERY)
10836         infoPtr->notifyFormat = SendMessageW(infoPtr->hwndNotify, WM_NOTIFYFORMAT, (WPARAM)infoPtr->hwndSelf, NF_QUERY);
10837 
10838     return infoPtr->notifyFormat;
10839 }
10840 
10841 /***
10842  * DESCRIPTION:
10843  * Paints/Repaints the listview control. Internal use.
10844  *
10845  * PARAMETER(S):
10846  * [I] infoPtr : valid pointer to the listview structure
10847  * [I] hdc : device context handle
10848  *
10849  * RETURN:
10850  * Zero
10851  */
10852 static LRESULT LISTVIEW_Paint(LISTVIEW_INFO *infoPtr, HDC hdc)
10853 {
10854     TRACE("(hdc=%p)\n", hdc);
10855 
10856     if (infoPtr->bNoItemMetrics && infoPtr->nItemCount)
10857     {
10858 	infoPtr->bNoItemMetrics = FALSE;
10859 	LISTVIEW_UpdateItemSize(infoPtr);
10860 	if (infoPtr->uView == LV_VIEW_ICON || infoPtr->uView == LV_VIEW_SMALLICON)
10861 	    LISTVIEW_Arrange(infoPtr, LVA_DEFAULT);
10862 	LISTVIEW_UpdateScroll(infoPtr);
10863     }
10864 
10865     if (infoPtr->hwndHeader)  UpdateWindow(infoPtr->hwndHeader);
10866 
10867     if (hdc)
10868         LISTVIEW_Refresh(infoPtr, hdc, NULL);
10869     else
10870     {
10871 	PAINTSTRUCT ps;
10872 
10873 	hdc = BeginPaint(infoPtr->hwndSelf, &ps);
10874 	if (!hdc) return 1;
10875 	LISTVIEW_Refresh(infoPtr, hdc, ps.fErase ? &ps.rcPaint : NULL);
10876 	EndPaint(infoPtr->hwndSelf, &ps);
10877     }
10878 
10879     return 0;
10880 }
10881 
10882 /***
10883  * DESCRIPTION:
10884  * Paints/Repaints the listview control, WM_PAINT handler.
10885  *
10886  * PARAMETER(S):
10887  * [I] infoPtr : valid pointer to the listview structure
10888  * [I] hdc : device context handle
10889  *
10890  * RETURN:
10891  * Zero
10892  */
10893 static inline LRESULT LISTVIEW_WMPaint(LISTVIEW_INFO *infoPtr, HDC hdc)
10894 {
10895     TRACE("(hdc=%p)\n", hdc);
10896 
10897     if (!is_redrawing(infoPtr))
10898         return DefWindowProcW (infoPtr->hwndSelf, WM_PAINT, (WPARAM)hdc, 0);
10899 
10900     return LISTVIEW_Paint(infoPtr, hdc);
10901 }
10902 
10903 /***
10904  * DESCRIPTION:
10905  * Paints/Repaints the listview control.
10906  *
10907  * PARAMETER(S):
10908  * [I] infoPtr : valid pointer to the listview structure
10909  * [I] hdc : device context handle
10910  * [I] options : drawing options
10911  *
10912  * RETURN:
10913  * Zero
10914  */
10915 static LRESULT LISTVIEW_PrintClient(LISTVIEW_INFO *infoPtr, HDC hdc, DWORD options)
10916 {
10917     if ((options & PRF_CHECKVISIBLE) && !IsWindowVisible(infoPtr->hwndSelf))
10918         return 0;
10919 
10920     if (options & ~(PRF_ERASEBKGND|PRF_CLIENT))
10921         FIXME("(hdc=%p options=0x%08x) partial stub\n", hdc, options);
10922 
10923     if (options & PRF_ERASEBKGND)
10924         LISTVIEW_EraseBkgnd(infoPtr, hdc);
10925 
10926     if (options & PRF_CLIENT)
10927         LISTVIEW_Paint(infoPtr, hdc);
10928 
10929     return 0;
10930 }
10931 
10932 
10933 /***
10934  * DESCRIPTION:
10935  * Processes double click messages (right mouse button).
10936  *
10937  * PARAMETER(S):
10938  * [I] infoPtr : valid pointer to the listview structure
10939  * [I] wKey : key flag
10940  * [I] x,y : mouse coordinate
10941  *
10942  * RETURN:
10943  * Zero
10944  */
10945 static LRESULT LISTVIEW_RButtonDblClk(const LISTVIEW_INFO *infoPtr, WORD wKey, INT x, INT y)
10946 {
10947     LVHITTESTINFO lvHitTestInfo;
10948 
10949     TRACE("(key=%hu,X=%u,Y=%u)\n", wKey, x, y);
10950 
10951     /* send NM_RELEASEDCAPTURE notification */
10952     if (!notify(infoPtr, NM_RELEASEDCAPTURE)) return 0;
10953 
10954     /* send NM_RDBLCLK notification */
10955     lvHitTestInfo.pt.x = x;
10956     lvHitTestInfo.pt.y = y;
10957     LISTVIEW_HitTest(infoPtr, &lvHitTestInfo, TRUE, FALSE);
10958     notify_click(infoPtr, NM_RDBLCLK, &lvHitTestInfo);
10959 
10960     return 0;
10961 }
10962 
10963 /***
10964  * DESCRIPTION:
10965  * Processes WM_RBUTTONDOWN message and corresponding drag operation.
10966  *
10967  * PARAMETER(S):
10968  * [I] infoPtr : valid pointer to the listview structure
10969  * [I] wKey : key flag
10970  * [I] x, y : mouse coordinate
10971  *
10972  * RETURN:
10973  * Zero
10974  */
10975 static LRESULT LISTVIEW_RButtonDown(LISTVIEW_INFO *infoPtr, WORD wKey, INT x, INT y)
10976 {
10977     LVHITTESTINFO ht;
10978     INT item;
10979 
10980     TRACE("(key=%hu, x=%d, y=%d)\n", wKey, x, y);
10981 
10982     /* send NM_RELEASEDCAPTURE notification */
10983     if (!notify(infoPtr, NM_RELEASEDCAPTURE)) return 0;
10984 
10985     /* determine the index of the selected item */
10986     ht.pt.x = x;
10987     ht.pt.y = y;
10988     item = LISTVIEW_HitTest(infoPtr, &ht, TRUE, TRUE);
10989 
10990     /* make sure the listview control window has the focus */
10991     if (!infoPtr->bFocus) SetFocus(infoPtr->hwndSelf);
10992 
10993     if ((item >= 0) && (item < infoPtr->nItemCount))
10994     {
10995 	LISTVIEW_SetItemFocus(infoPtr, item);
10996 	if (!((wKey & MK_SHIFT) || (wKey & MK_CONTROL)) &&
10997             !LISTVIEW_GetItemState(infoPtr, item, LVIS_SELECTED))
10998 	    LISTVIEW_SetSelection(infoPtr, item);
10999     }
11000     else
11001 	LISTVIEW_DeselectAll(infoPtr);
11002 
11003     if (LISTVIEW_TrackMouse(infoPtr, ht.pt))
11004     {
11005 	if (ht.iItem != -1)
11006 	{
11007             NMLISTVIEW nmlv;
11008 
11009             memset(&nmlv, 0, sizeof(nmlv));
11010             nmlv.iItem = ht.iItem;
11011             nmlv.ptAction = ht.pt;
11012 
11013             notify_listview(infoPtr, LVN_BEGINRDRAG, &nmlv);
11014 	}
11015     }
11016     else
11017     {
11018 	SetFocus(infoPtr->hwndSelf);
11019 
11020         ht.pt.x = x;
11021         ht.pt.y = y;
11022         LISTVIEW_HitTest(infoPtr, &ht, TRUE, FALSE);
11023 
11024 	if (notify_click(infoPtr, NM_RCLICK, &ht))
11025 	{
11026 	    /* Send a WM_CONTEXTMENU message in response to the WM_RBUTTONUP */
11027 	    SendMessageW(infoPtr->hwndSelf, WM_CONTEXTMENU,
11028 		(WPARAM)infoPtr->hwndSelf, (LPARAM)GetMessagePos());
11029 	}
11030     }
11031 
11032     return 0;
11033 }
11034 
11035 /***
11036  * DESCRIPTION:
11037  * Sets the cursor.
11038  *
11039  * PARAMETER(S):
11040  * [I] infoPtr : valid pointer to the listview structure
11041  * [I] hwnd : window handle of window containing the cursor
11042  * [I] nHittest : hit-test code
11043  * [I] wMouseMsg : ideintifier of the mouse message
11044  *
11045  * RETURN:
11046  * TRUE if cursor is set
11047  * FALSE otherwise
11048  */
11049 static BOOL LISTVIEW_SetCursor(const LISTVIEW_INFO *infoPtr, WPARAM wParam, LPARAM lParam)
11050 {
11051     LVHITTESTINFO lvHitTestInfo;
11052 
11053     if (!LISTVIEW_IsHotTracking(infoPtr)) goto forward;
11054 
11055     if (!infoPtr->hHotCursor) goto forward;
11056 
11057     GetCursorPos(&lvHitTestInfo.pt);
11058     if (LISTVIEW_HitTest(infoPtr, &lvHitTestInfo, FALSE, FALSE) < 0) goto forward;
11059 
11060     SetCursor(infoPtr->hHotCursor);
11061 
11062     return TRUE;
11063 
11064 forward:
11065 
11066     return DefWindowProcW(infoPtr->hwndSelf, WM_SETCURSOR, wParam, lParam);
11067 }
11068 
11069 /***
11070  * DESCRIPTION:
11071  * Sets the focus.
11072  *
11073  * PARAMETER(S):
11074  * [I] infoPtr : valid pointer to the listview structure
11075  * [I] hwndLoseFocus : handle of previously focused window
11076  *
11077  * RETURN:
11078  * Zero
11079  */
11080 static LRESULT LISTVIEW_SetFocus(LISTVIEW_INFO *infoPtr, HWND hwndLoseFocus)
11081 {
11082     TRACE("(hwndLoseFocus=%p)\n", hwndLoseFocus);
11083 
11084     /* if we have the focus already, there's nothing to do */
11085     if (infoPtr->bFocus) return 0;
11086 
11087     /* send NM_SETFOCUS notification */
11088     if (!notify(infoPtr, NM_SETFOCUS)) return 0;
11089 
11090     /* set window focus flag */
11091     infoPtr->bFocus = TRUE;
11092 
11093     /* put the focus rect back on */
11094     LISTVIEW_ShowFocusRect(infoPtr, TRUE);
11095 
11096     /* redraw all visible selected items */
11097     LISTVIEW_InvalidateSelectedItems(infoPtr);
11098 
11099     return 0;
11100 }
11101 
11102 /***
11103  * DESCRIPTION:
11104  * Sets the font.
11105  *
11106  * PARAMETER(S):
11107  * [I] infoPtr : valid pointer to the listview structure
11108  * [I] fRedraw : font handle
11109  * [I] fRedraw : redraw flag
11110  *
11111  * RETURN:
11112  * Zero
11113  */
11114 static LRESULT LISTVIEW_SetFont(LISTVIEW_INFO *infoPtr, HFONT hFont, WORD fRedraw)
11115 {
11116     HFONT oldFont = infoPtr->hFont;
11117     INT oldHeight = infoPtr->nItemHeight;
11118 
11119     TRACE("(hfont=%p,redraw=%hu)\n", hFont, fRedraw);
11120 
11121     infoPtr->hFont = hFont ? hFont : infoPtr->hDefaultFont;
11122     if (infoPtr->hFont == oldFont) return 0;
11123 
11124     LISTVIEW_SaveTextMetrics(infoPtr);
11125 
11126     infoPtr->nItemHeight = LISTVIEW_CalculateItemHeight(infoPtr);
11127 
11128     if (infoPtr->uView == LV_VIEW_DETAILS)
11129     {
11130 	SendMessageW(infoPtr->hwndHeader, WM_SETFONT, (WPARAM)hFont, MAKELPARAM(fRedraw, 0));
11131         LISTVIEW_UpdateSize(infoPtr);
11132         LISTVIEW_UpdateScroll(infoPtr);
11133     }
11134     else if (infoPtr->nItemHeight != oldHeight)
11135         LISTVIEW_UpdateScroll(infoPtr);
11136 
11137     if (fRedraw) LISTVIEW_InvalidateList(infoPtr);
11138 
11139     return 0;
11140 }
11141 
11142 /***
11143  * DESCRIPTION:
11144  * Message handling for WM_SETREDRAW.
11145  * For the Listview, it invalidates the entire window (the doc specifies otherwise)
11146  *
11147  * PARAMETER(S):
11148  * [I] infoPtr : valid pointer to the listview structure
11149  * [I] redraw: state of redraw flag
11150  *
11151  * RETURN:
11152  *     Zero.
11153  */
11154 static LRESULT LISTVIEW_SetRedraw(LISTVIEW_INFO *infoPtr, BOOL redraw)
11155 {
11156     TRACE("old=%d, new=%d\n", infoPtr->redraw, redraw);
11157 
11158     if (infoPtr->redraw == !!redraw)
11159         return 0;
11160 
11161     if (!(infoPtr->redraw = !!redraw))
11162         return 0;
11163 
11164     if (is_autoarrange(infoPtr))
11165 	LISTVIEW_Arrange(infoPtr, LVA_DEFAULT);
11166     LISTVIEW_UpdateScroll(infoPtr);
11167 
11168     /* despite what the WM_SETREDRAW docs says, apps expect us
11169      * to invalidate the listview here... stupid! */
11170     LISTVIEW_InvalidateList(infoPtr);
11171 
11172     return 0;
11173 }
11174 
11175 /***
11176  * DESCRIPTION:
11177  * Resizes the listview control. This function processes WM_SIZE
11178  * messages.  At this time, the width and height are not used.
11179  *
11180  * PARAMETER(S):
11181  * [I] infoPtr : valid pointer to the listview structure
11182  * [I] Width : new width
11183  * [I] Height : new height
11184  *
11185  * RETURN:
11186  * Zero
11187  */
11188 static LRESULT LISTVIEW_Size(LISTVIEW_INFO *infoPtr, int Width, int Height)
11189 {
11190     RECT rcOld = infoPtr->rcList;
11191 
11192     TRACE("(width=%d, height=%d)\n", Width, Height);
11193 
11194     LISTVIEW_UpdateSize(infoPtr);
11195     if (EqualRect(&rcOld, &infoPtr->rcList)) return 0;
11196 
11197     /* do not bother with display related stuff if we're not redrawing */
11198     if (!is_redrawing(infoPtr)) return 0;
11199 
11200     if (is_autoarrange(infoPtr))
11201 	LISTVIEW_Arrange(infoPtr, LVA_DEFAULT);
11202 
11203     LISTVIEW_UpdateScroll(infoPtr);
11204 
11205     /* refresh all only for lists whose height changed significantly */
11206     if ((infoPtr->uView == LV_VIEW_LIST) &&
11207 	(rcOld.bottom - rcOld.top) / infoPtr->nItemHeight !=
11208 	(infoPtr->rcList.bottom - infoPtr->rcList.top) / infoPtr->nItemHeight)
11209 	LISTVIEW_InvalidateList(infoPtr);
11210 
11211   return 0;
11212 }
11213 
11214 /***
11215  * DESCRIPTION:
11216  * Sets the size information.
11217  *
11218  * PARAMETER(S):
11219  * [I] infoPtr : valid pointer to the listview structure
11220  *
11221  * RETURN:
11222  *  None
11223  */
11224 static void LISTVIEW_UpdateSize(LISTVIEW_INFO *infoPtr)
11225 {
11226     TRACE("uView=%d, rcList(old)=%s\n", infoPtr->uView, wine_dbgstr_rect(&infoPtr->rcList));
11227 
11228     GetClientRect(infoPtr->hwndSelf, &infoPtr->rcList);
11229 
11230     if (infoPtr->uView == LV_VIEW_LIST)
11231     {
11232 	/* Apparently the "LIST" style is supposed to have the same
11233 	 * number of items in a column even if there is no scroll bar.
11234 	 * Since if a scroll bar already exists then the bottom is already
11235 	 * reduced, only reduce if the scroll bar does not currently exist.
11236 	 * The "2" is there to mimic the native control. I think it may be
11237 	 * related to either padding or edges.  (GLA 7/2002)
11238 	 */
11239 	if (!(GetWindowLongW(infoPtr->hwndSelf, GWL_STYLE) & WS_HSCROLL))
11240 	    infoPtr->rcList.bottom -= GetSystemMetrics(SM_CYHSCROLL);
11241         infoPtr->rcList.bottom = max (infoPtr->rcList.bottom - 2, 0);
11242     }
11243 
11244     /* When ListView control is created invisible, header isn't created right away. */
11245     if (infoPtr->hwndHeader)
11246     {
11247         POINT origin;
11248         WINDOWPOS wp;
11249         HDLAYOUT hl;
11250         RECT rect;
11251 
11252         LISTVIEW_GetOrigin(infoPtr, &origin);
11253 
11254         rect = infoPtr->rcList;
11255         rect.left += origin.x;
11256 
11257         hl.prc = &rect;
11258 	hl.pwpos = &wp;
11259 	SendMessageW( infoPtr->hwndHeader, HDM_LAYOUT, 0, (LPARAM)&hl );
11260 	TRACE("  wp.flags=0x%08x, wp=%d,%d (%dx%d)\n", wp.flags, wp.x, wp.y, wp.cx, wp.cy);
11261 
11262 	if (LISTVIEW_IsHeaderEnabled(infoPtr))
11263 	    wp.flags |= SWP_SHOWWINDOW;
11264 	else
11265 	{
11266 	    wp.flags |= SWP_HIDEWINDOW;
11267 	    wp.cy = 0;
11268 	}
11269 
11270 	SetWindowPos(wp.hwnd, wp.hwndInsertAfter, wp.x, wp.y, wp.cx, wp.cy, wp.flags);
11271 	TRACE("  after SWP wp=%d,%d (%dx%d)\n", wp.x, wp.y, wp.cx, wp.cy);
11272 
11273 	infoPtr->rcList.top = max(wp.cy, 0);
11274     }
11275     /* extra padding for grid */
11276     if (infoPtr->uView == LV_VIEW_DETAILS && infoPtr->dwLvExStyle & LVS_EX_GRIDLINES)
11277 	infoPtr->rcList.top += 2;
11278 
11279     TRACE("  rcList=%s\n", wine_dbgstr_rect(&infoPtr->rcList));
11280 }
11281 
11282 /***
11283  * DESCRIPTION:
11284  * Processes WM_STYLECHANGED messages.
11285  *
11286  * PARAMETER(S):
11287  * [I] infoPtr : valid pointer to the listview structure
11288  * [I] wStyleType : window style type (normal or extended)
11289  * [I] lpss : window style information
11290  *
11291  * RETURN:
11292  * Zero
11293  */
11294 static INT LISTVIEW_StyleChanged(LISTVIEW_INFO *infoPtr, WPARAM wStyleType,
11295                                  const STYLESTRUCT *lpss)
11296 {
11297     UINT uNewView, uOldView;
11298     UINT style;
11299 
11300     TRACE("(styletype=%lx, styleOld=0x%08x, styleNew=0x%08x)\n",
11301           wStyleType, lpss->styleOld, lpss->styleNew);
11302 
11303     if (wStyleType != GWL_STYLE || lpss->styleNew == infoPtr->dwStyle) return 0;
11304 
11305     infoPtr->dwStyle = lpss->styleNew;
11306 
11307     if (((lpss->styleOld & WS_HSCROLL) != 0)&&
11308         ((lpss->styleNew & WS_HSCROLL) == 0))
11309        ShowScrollBar(infoPtr->hwndSelf, SB_HORZ, FALSE);
11310 
11311     if (((lpss->styleOld & WS_VSCROLL) != 0)&&
11312         ((lpss->styleNew & WS_VSCROLL) == 0))
11313        ShowScrollBar(infoPtr->hwndSelf, SB_VERT, FALSE);
11314 
11315     uNewView = lpss->styleNew & LVS_TYPEMASK;
11316     uOldView = lpss->styleOld & LVS_TYPEMASK;
11317 
11318     if (uNewView != uOldView)
11319     {
11320     	HIMAGELIST himl;
11321 
11322         /* LVM_SETVIEW doesn't change window style bits within LVS_TYPEMASK,
11323            changing style updates current view only when view bits change. */
11324         map_style_view(infoPtr);
11325         SendMessageW(infoPtr->hwndEdit, WM_KILLFOCUS, 0, 0);
11326     	ShowWindow(infoPtr->hwndHeader, SW_HIDE);
11327 
11328         ShowScrollBar(infoPtr->hwndSelf, SB_BOTH, FALSE);
11329         SetRectEmpty(&infoPtr->rcFocus);
11330 
11331         himl = (uNewView == LVS_ICON ? infoPtr->himlNormal : infoPtr->himlSmall);
11332         set_icon_size(&infoPtr->iconSize, himl, uNewView != LVS_ICON);
11333 
11334         if (uNewView == LVS_REPORT)
11335         {
11336             HDLAYOUT hl;
11337             WINDOWPOS wp;
11338 
11339             LISTVIEW_CreateHeader( infoPtr );
11340 
11341             hl.prc = &infoPtr->rcList;
11342             hl.pwpos = &wp;
11343             SendMessageW( infoPtr->hwndHeader, HDM_LAYOUT, 0, (LPARAM)&hl );
11344             SetWindowPos(infoPtr->hwndHeader, infoPtr->hwndSelf, wp.x, wp.y, wp.cx, wp.cy,
11345                     wp.flags | ((infoPtr->dwStyle & LVS_NOCOLUMNHEADER)
11346                         ? SWP_HIDEWINDOW : SWP_SHOWWINDOW));
11347         }
11348 
11349 	LISTVIEW_UpdateItemSize(infoPtr);
11350     }
11351 
11352     if (uNewView == LVS_REPORT || infoPtr->dwLvExStyle & LVS_EX_HEADERINALLVIEWS)
11353     {
11354         if ((lpss->styleOld ^ lpss->styleNew) & LVS_NOCOLUMNHEADER)
11355         {
11356             if (lpss->styleNew & LVS_NOCOLUMNHEADER)
11357             {
11358                 /* Turn off the header control */
11359                 style = GetWindowLongW(infoPtr->hwndHeader, GWL_STYLE);
11360                 TRACE("Hide header control, was 0x%08x\n", style);
11361                 SetWindowLongW(infoPtr->hwndHeader, GWL_STYLE, style | HDS_HIDDEN);
11362             } else {
11363                 /* Turn on the header control */
11364                 if ((style = GetWindowLongW(infoPtr->hwndHeader, GWL_STYLE)) & HDS_HIDDEN)
11365                 {
11366                     TRACE("Show header control, was 0x%08x\n", style);
11367                     SetWindowLongW(infoPtr->hwndHeader, GWL_STYLE, (style & ~HDS_HIDDEN) | WS_VISIBLE);
11368                 }
11369             }
11370         }
11371     }
11372 
11373     if ( (uNewView == LVS_ICON || uNewView == LVS_SMALLICON) &&
11374 	 (uNewView != uOldView || ((lpss->styleNew ^ lpss->styleOld) & LVS_ALIGNMASK)) )
11375 	 LISTVIEW_Arrange(infoPtr, LVA_DEFAULT);
11376 
11377     /* update the size of the client area */
11378     LISTVIEW_UpdateSize(infoPtr);
11379 
11380     /* add scrollbars if needed */
11381     LISTVIEW_UpdateScroll(infoPtr);
11382 
11383     /* invalidate client area + erase background */
11384     LISTVIEW_InvalidateList(infoPtr);
11385 
11386     return 0;
11387 }
11388 
11389 /***
11390  * DESCRIPTION:
11391  * Processes WM_STYLECHANGING messages.
11392  *
11393  * PARAMETER(S):
11394  * [I] wStyleType : window style type (normal or extended)
11395  * [I0] lpss : window style information
11396  *
11397  * RETURN:
11398  * Zero
11399  */
11400 static INT LISTVIEW_StyleChanging(WPARAM wStyleType,
11401                                   STYLESTRUCT *lpss)
11402 {
11403     TRACE("(styletype=%lx, styleOld=0x%08x, styleNew=0x%08x)\n",
11404           wStyleType, lpss->styleOld, lpss->styleNew);
11405 
11406     /* don't forward LVS_OWNERDATA only if not already set to */
11407     if ((lpss->styleNew ^ lpss->styleOld) & LVS_OWNERDATA)
11408     {
11409         if (lpss->styleOld & LVS_OWNERDATA)
11410             lpss->styleNew |= LVS_OWNERDATA;
11411         else
11412             lpss->styleNew &= ~LVS_OWNERDATA;
11413     }
11414 
11415     return 0;
11416 }
11417 
11418 /***
11419  * DESCRIPTION:
11420  * Processes WM_SHOWWINDOW messages.
11421  *
11422  * PARAMETER(S):
11423  * [I] infoPtr : valid pointer to the listview structure
11424  * [I] bShown  : window is being shown (FALSE when hidden)
11425  * [I] iStatus : window show status
11426  *
11427  * RETURN:
11428  * Zero
11429  */
11430 static LRESULT LISTVIEW_ShowWindow(LISTVIEW_INFO *infoPtr, WPARAM bShown, LPARAM iStatus)
11431 {
11432   /* header delayed creation */
11433   if ((infoPtr->uView == LV_VIEW_DETAILS) && bShown)
11434   {
11435     LISTVIEW_CreateHeader(infoPtr);
11436 
11437     if (!(LVS_NOCOLUMNHEADER & infoPtr->dwStyle))
11438       ShowWindow(infoPtr->hwndHeader, SW_SHOWNORMAL);
11439   }
11440 
11441   return DefWindowProcW(infoPtr->hwndSelf, WM_SHOWWINDOW, bShown, iStatus);
11442 }
11443 
11444 /***
11445  * DESCRIPTION:
11446  * Processes CCM_GETVERSION messages.
11447  *
11448  * PARAMETER(S):
11449  * [I] infoPtr : valid pointer to the listview structure
11450  *
11451  * RETURN:
11452  * Current version
11453  */
11454 static inline LRESULT LISTVIEW_GetVersion(const LISTVIEW_INFO *infoPtr)
11455 {
11456   return infoPtr->iVersion;
11457 }
11458 
11459 /***
11460  * DESCRIPTION:
11461  * Processes CCM_SETVERSION messages.
11462  *
11463  * PARAMETER(S):
11464  * [I] infoPtr  : valid pointer to the listview structure
11465  * [I] iVersion : version to be set
11466  *
11467  * RETURN:
11468  * -1 when requested version is greater than DLL version;
11469  * previous version otherwise
11470  */
11471 static LRESULT LISTVIEW_SetVersion(LISTVIEW_INFO *infoPtr, DWORD iVersion)
11472 {
11473   INT iOldVersion = infoPtr->iVersion;
11474 
11475   if (iVersion > COMCTL32_VERSION)
11476     return -1;
11477 
11478   infoPtr->iVersion = iVersion;
11479 
11480   TRACE("new version %d\n", iVersion);
11481 
11482   return iOldVersion;
11483 }
11484 
11485 /***
11486  * DESCRIPTION:
11487  * Window procedure of the listview control.
11488  *
11489  */
11490 static LRESULT WINAPI
11491 LISTVIEW_WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
11492 {
11493   LISTVIEW_INFO *infoPtr = (LISTVIEW_INFO *)GetWindowLongPtrW(hwnd, 0);
11494 
11495   TRACE("(hwnd=%p uMsg=%x wParam=%lx lParam=%lx)\n", hwnd, uMsg, wParam, lParam);
11496 
11497   if (!infoPtr && (uMsg != WM_NCCREATE))
11498     return DefWindowProcW(hwnd, uMsg, wParam, lParam);
11499 
11500   switch (uMsg)
11501   {
11502   case LVM_APPROXIMATEVIEWRECT:
11503     return LISTVIEW_ApproximateViewRect(infoPtr, (INT)wParam,
11504                                         LOWORD(lParam), HIWORD(lParam));
11505   case LVM_ARRANGE:
11506     return LISTVIEW_Arrange(infoPtr, (INT)wParam);
11507 
11508   case LVM_CANCELEDITLABEL:
11509     return LISTVIEW_CancelEditLabel(infoPtr);
11510 
11511   case LVM_CREATEDRAGIMAGE:
11512     return (LRESULT)LISTVIEW_CreateDragImage(infoPtr, (INT)wParam, (LPPOINT)lParam);
11513 
11514   case LVM_DELETEALLITEMS:
11515     return LISTVIEW_DeleteAllItems(infoPtr, FALSE);
11516 
11517   case LVM_DELETECOLUMN:
11518     return LISTVIEW_DeleteColumn(infoPtr, (INT)wParam);
11519 
11520   case LVM_DELETEITEM:
11521     return LISTVIEW_DeleteItem(infoPtr, (INT)wParam);
11522 
11523   case LVM_EDITLABELA:
11524   case LVM_EDITLABELW:
11525     return (LRESULT)LISTVIEW_EditLabelT(infoPtr, (INT)wParam,
11526                                         uMsg == LVM_EDITLABELW);
11527   /* case LVM_ENABLEGROUPVIEW: */
11528 
11529   case LVM_ENSUREVISIBLE:
11530     return LISTVIEW_EnsureVisible(infoPtr, (INT)wParam, (BOOL)lParam);
11531 
11532   case LVM_FINDITEMW:
11533     return LISTVIEW_FindItemW(infoPtr, (INT)wParam, (LPLVFINDINFOW)lParam);
11534 
11535   case LVM_FINDITEMA:
11536     return LISTVIEW_FindItemA(infoPtr, (INT)wParam, (LPLVFINDINFOA)lParam);
11537 
11538   case LVM_GETBKCOLOR:
11539     return infoPtr->clrBk;
11540 
11541   /* case LVM_GETBKIMAGE: */
11542 
11543   case LVM_GETCALLBACKMASK:
11544     return infoPtr->uCallbackMask;
11545 
11546   case LVM_GETCOLUMNA:
11547   case LVM_GETCOLUMNW:
11548     return LISTVIEW_GetColumnT(infoPtr, (INT)wParam, (LPLVCOLUMNW)lParam,
11549                                uMsg == LVM_GETCOLUMNW);
11550 
11551   case LVM_GETCOLUMNORDERARRAY:
11552     return LISTVIEW_GetColumnOrderArray(infoPtr, (INT)wParam, (LPINT)lParam);
11553 
11554   case LVM_GETCOLUMNWIDTH:
11555     return LISTVIEW_GetColumnWidth(infoPtr, (INT)wParam);
11556 
11557   case LVM_GETCOUNTPERPAGE:
11558     return LISTVIEW_GetCountPerPage(infoPtr);
11559 
11560   case LVM_GETEDITCONTROL:
11561     return (LRESULT)infoPtr->hwndEdit;
11562 
11563   case LVM_GETEXTENDEDLISTVIEWSTYLE:
11564     return infoPtr->dwLvExStyle;
11565 
11566   /* case LVM_GETGROUPINFO: */
11567 
11568   /* case LVM_GETGROUPMETRICS: */
11569 
11570   case LVM_GETHEADER:
11571     return (LRESULT)infoPtr->hwndHeader;
11572 
11573   case LVM_GETHOTCURSOR:
11574     return (LRESULT)infoPtr->hHotCursor;
11575 
11576   case LVM_GETHOTITEM:
11577     return infoPtr->nHotItem;
11578 
11579   case LVM_GETHOVERTIME:
11580     return infoPtr->dwHoverTime;
11581 
11582   case LVM_GETIMAGELIST:
11583     return (LRESULT)LISTVIEW_GetImageList(infoPtr, (INT)wParam);
11584 
11585   /* case LVM_GETINSERTMARK: */
11586 
11587   /* case LVM_GETINSERTMARKCOLOR: */
11588 
11589   /* case LVM_GETINSERTMARKRECT: */
11590 
11591   case LVM_GETISEARCHSTRINGA:
11592   case LVM_GETISEARCHSTRINGW:
11593     FIXME("LVM_GETISEARCHSTRING: unimplemented\n");
11594     return FALSE;
11595 
11596   case LVM_GETITEMA:
11597   case LVM_GETITEMW:
11598     return LISTVIEW_GetItemExtT(infoPtr, (LPLVITEMW)lParam, uMsg == LVM_GETITEMW);
11599 
11600   case LVM_GETITEMCOUNT:
11601     return infoPtr->nItemCount;
11602 
11603   case LVM_GETITEMPOSITION:
11604     return LISTVIEW_GetItemPosition(infoPtr, (INT)wParam, (LPPOINT)lParam);
11605 
11606   case LVM_GETITEMRECT:
11607     return LISTVIEW_GetItemRect(infoPtr, (INT)wParam, (LPRECT)lParam);
11608 
11609   case LVM_GETITEMSPACING:
11610     return LISTVIEW_GetItemSpacing(infoPtr, (BOOL)wParam);
11611 
11612   case LVM_GETITEMSTATE:
11613     return LISTVIEW_GetItemState(infoPtr, (INT)wParam, (UINT)lParam);
11614 
11615   case LVM_GETITEMTEXTA:
11616   case LVM_GETITEMTEXTW:
11617     return LISTVIEW_GetItemTextT(infoPtr, (INT)wParam, (LPLVITEMW)lParam,
11618                                  uMsg == LVM_GETITEMTEXTW);
11619 
11620   case LVM_GETNEXTITEM:
11621     return LISTVIEW_GetNextItem(infoPtr, (INT)wParam, LOWORD(lParam));
11622 
11623   case LVM_GETNUMBEROFWORKAREAS:
11624     FIXME("LVM_GETNUMBEROFWORKAREAS: unimplemented\n");
11625     return 1;
11626 
11627   case LVM_GETORIGIN:
11628     if (!lParam) return FALSE;
11629     if (infoPtr->uView == LV_VIEW_DETAILS ||
11630         infoPtr->uView == LV_VIEW_LIST) return FALSE;
11631     LISTVIEW_GetOrigin(infoPtr, (LPPOINT)lParam);
11632     return TRUE;
11633 
11634   /* case LVM_GETOUTLINECOLOR: */
11635 
11636   /* case LVM_GETSELECTEDCOLUMN: */
11637 
11638   case LVM_GETSELECTEDCOUNT:
11639     return LISTVIEW_GetSelectedCount(infoPtr);
11640 
11641   case LVM_GETSELECTIONMARK:
11642     return infoPtr->nSelectionMark;
11643 
11644   case LVM_GETSTRINGWIDTHA:
11645   case LVM_GETSTRINGWIDTHW:
11646     return LISTVIEW_GetStringWidthT(infoPtr, (LPCWSTR)lParam,
11647                                     uMsg == LVM_GETSTRINGWIDTHW);
11648 
11649   case LVM_GETSUBITEMRECT:
11650     return LISTVIEW_GetSubItemRect(infoPtr, (UINT)wParam, (LPRECT)lParam);
11651 
11652   case LVM_GETTEXTBKCOLOR:
11653     return infoPtr->clrTextBk;
11654 
11655   case LVM_GETTEXTCOLOR:
11656     return infoPtr->clrText;
11657 
11658   /* case LVM_GETTILEINFO: */
11659 
11660   /* case LVM_GETTILEVIEWINFO: */
11661 
11662   case LVM_GETTOOLTIPS:
11663     if( !infoPtr->hwndToolTip )
11664         infoPtr->hwndToolTip = COMCTL32_CreateToolTip( hwnd );
11665     return (LRESULT)infoPtr->hwndToolTip;
11666 
11667   case LVM_GETTOPINDEX:
11668     return LISTVIEW_GetTopIndex(infoPtr);
11669 
11670   case LVM_GETUNICODEFORMAT:
11671     return (infoPtr->notifyFormat == NFR_UNICODE);
11672 
11673   case LVM_GETVIEW:
11674     return infoPtr->uView;
11675 
11676   case LVM_GETVIEWRECT:
11677     return LISTVIEW_GetViewRect(infoPtr, (LPRECT)lParam);
11678 
11679   case LVM_GETWORKAREAS:
11680     FIXME("LVM_GETWORKAREAS: unimplemented\n");
11681     return FALSE;
11682 
11683   /* case LVM_HASGROUP: */
11684 
11685   case LVM_HITTEST:
11686     return LISTVIEW_HitTest(infoPtr, (LPLVHITTESTINFO)lParam, FALSE, TRUE);
11687 
11688   case LVM_INSERTCOLUMNA:
11689   case LVM_INSERTCOLUMNW:
11690     return LISTVIEW_InsertColumnT(infoPtr, (INT)wParam, (LPLVCOLUMNW)lParam,
11691                                   uMsg == LVM_INSERTCOLUMNW);
11692 
11693   /* case LVM_INSERTGROUP: */
11694 
11695   /* case LVM_INSERTGROUPSORTED: */
11696 
11697   case LVM_INSERTITEMA:
11698   case LVM_INSERTITEMW:
11699     return LISTVIEW_InsertItemT(infoPtr, (LPLVITEMW)lParam, uMsg == LVM_INSERTITEMW);
11700 
11701   /* case LVM_INSERTMARKHITTEST: */
11702 
11703   /* case LVM_ISGROUPVIEWENABLED: */
11704 
11705   case LVM_ISITEMVISIBLE:
11706     return LISTVIEW_IsItemVisible(infoPtr, (INT)wParam);
11707 
11708   case LVM_MAPIDTOINDEX:
11709     return LISTVIEW_MapIdToIndex(infoPtr, (UINT)wParam);
11710 
11711   case LVM_MAPINDEXTOID:
11712     return LISTVIEW_MapIndexToId(infoPtr, (INT)wParam);
11713 
11714   /* case LVM_MOVEGROUP: */
11715 
11716   /* case LVM_MOVEITEMTOGROUP: */
11717 
11718   case LVM_REDRAWITEMS:
11719     return LISTVIEW_RedrawItems(infoPtr, (INT)wParam, (INT)lParam);
11720 
11721   /* case LVM_REMOVEALLGROUPS: */
11722 
11723   /* case LVM_REMOVEGROUP: */
11724 
11725   case LVM_SCROLL:
11726     return LISTVIEW_Scroll(infoPtr, (INT)wParam, (INT)lParam);
11727 
11728   case LVM_SETBKCOLOR:
11729     return LISTVIEW_SetBkColor(infoPtr, (COLORREF)lParam);
11730 
11731   /* case LVM_SETBKIMAGE: */
11732 
11733   case LVM_SETCALLBACKMASK:
11734     infoPtr->uCallbackMask = (UINT)wParam;
11735     return TRUE;
11736 
11737   case LVM_SETCOLUMNA:
11738   case LVM_SETCOLUMNW:
11739     return LISTVIEW_SetColumnT(infoPtr, (INT)wParam, (LPLVCOLUMNW)lParam,
11740                                uMsg == LVM_SETCOLUMNW);
11741 
11742   case LVM_SETCOLUMNORDERARRAY:
11743     return LISTVIEW_SetColumnOrderArray(infoPtr, (INT)wParam, (LPINT)lParam);
11744 
11745   case LVM_SETCOLUMNWIDTH:
11746     return LISTVIEW_SetColumnWidth(infoPtr, (INT)wParam, (short)LOWORD(lParam));
11747 
11748   case LVM_SETEXTENDEDLISTVIEWSTYLE:
11749     return LISTVIEW_SetExtendedListViewStyle(infoPtr, (DWORD)wParam, (DWORD)lParam);
11750 
11751   /* case LVM_SETGROUPINFO: */
11752 
11753   /* case LVM_SETGROUPMETRICS: */
11754 
11755   case LVM_SETHOTCURSOR:
11756     return (LRESULT)LISTVIEW_SetHotCursor(infoPtr, (HCURSOR)lParam);
11757 
11758   case LVM_SETHOTITEM:
11759     return LISTVIEW_SetHotItem(infoPtr, (INT)wParam);
11760 
11761   case LVM_SETHOVERTIME:
11762     return LISTVIEW_SetHoverTime(infoPtr, (DWORD)lParam);
11763 
11764   case LVM_SETICONSPACING:
11765     if(lParam == -1)
11766         return LISTVIEW_SetIconSpacing(infoPtr, -1, -1);
11767     return LISTVIEW_SetIconSpacing(infoPtr, LOWORD(lParam), HIWORD(lParam));
11768 
11769   case LVM_SETIMAGELIST:
11770     return (LRESULT)LISTVIEW_SetImageList(infoPtr, (INT)wParam, (HIMAGELIST)lParam);
11771 
11772   /* case LVM_SETINFOTIP: */
11773 
11774   /* case LVM_SETINSERTMARK: */
11775 
11776   /* case LVM_SETINSERTMARKCOLOR: */
11777 
11778   case LVM_SETITEMA:
11779   case LVM_SETITEMW:
11780     {
11781 	if (infoPtr->dwStyle & LVS_OWNERDATA) return FALSE;
11782 	return LISTVIEW_SetItemT(infoPtr, (LPLVITEMW)lParam, (uMsg == LVM_SETITEMW));
11783     }
11784 
11785   case LVM_SETITEMCOUNT:
11786     return LISTVIEW_SetItemCount(infoPtr, (INT)wParam, (DWORD)lParam);
11787 
11788   case LVM_SETITEMPOSITION:
11789     {
11790 	POINT pt;
11791         pt.x = (short)LOWORD(lParam);
11792         pt.y = (short)HIWORD(lParam);
11793         return LISTVIEW_SetItemPosition(infoPtr, (INT)wParam, &pt);
11794     }
11795 
11796   case LVM_SETITEMPOSITION32:
11797     return LISTVIEW_SetItemPosition(infoPtr, (INT)wParam, (POINT*)lParam);
11798 
11799   case LVM_SETITEMSTATE:
11800     return LISTVIEW_SetItemState(infoPtr, (INT)wParam, (LPLVITEMW)lParam);
11801 
11802   case LVM_SETITEMTEXTA:
11803   case LVM_SETITEMTEXTW:
11804     return LISTVIEW_SetItemTextT(infoPtr, (INT)wParam, (LPLVITEMW)lParam,
11805                                  uMsg == LVM_SETITEMTEXTW);
11806 
11807   /* case LVM_SETOUTLINECOLOR: */
11808 
11809   /* case LVM_SETSELECTEDCOLUMN: */
11810 
11811   case LVM_SETSELECTIONMARK:
11812     return LISTVIEW_SetSelectionMark(infoPtr, (INT)lParam);
11813 
11814   case LVM_SETTEXTBKCOLOR:
11815     return LISTVIEW_SetTextBkColor(infoPtr, (COLORREF)lParam);
11816 
11817   case LVM_SETTEXTCOLOR:
11818     return LISTVIEW_SetTextColor(infoPtr, (COLORREF)lParam);
11819 
11820   /* case LVM_SETTILEINFO: */
11821 
11822   /* case LVM_SETTILEVIEWINFO: */
11823 
11824   /* case LVM_SETTILEWIDTH: */
11825 
11826   case LVM_SETTOOLTIPS:
11827     return (LRESULT)LISTVIEW_SetToolTips(infoPtr, (HWND)lParam);
11828 
11829   case LVM_SETUNICODEFORMAT:
11830     return LISTVIEW_SetUnicodeFormat(infoPtr, wParam);
11831 
11832   case LVM_SETVIEW:
11833     return LISTVIEW_SetView(infoPtr, wParam);
11834 
11835   /* case LVM_SETWORKAREAS: */
11836 
11837   /* case LVM_SORTGROUPS: */
11838 
11839   case LVM_SORTITEMS:
11840   case LVM_SORTITEMSEX:
11841     return LISTVIEW_SortItems(infoPtr, (PFNLVCOMPARE)lParam, wParam,
11842                               uMsg == LVM_SORTITEMSEX);
11843   case LVM_SUBITEMHITTEST:
11844     return LISTVIEW_HitTest(infoPtr, (LPLVHITTESTINFO)lParam, TRUE, FALSE);
11845 
11846   case LVM_UPDATE:
11847     return LISTVIEW_Update(infoPtr, (INT)wParam);
11848 
11849   case CCM_GETVERSION:
11850     return LISTVIEW_GetVersion(infoPtr);
11851 
11852   case CCM_SETVERSION:
11853     return LISTVIEW_SetVersion(infoPtr, wParam);
11854 
11855   case WM_CHAR:
11856     return LISTVIEW_ProcessLetterKeys( infoPtr, wParam, lParam );
11857 
11858   case WM_COMMAND:
11859     return LISTVIEW_Command(infoPtr, wParam, lParam);
11860 
11861   case WM_NCCREATE:
11862     return LISTVIEW_NCCreate(hwnd, wParam, (LPCREATESTRUCTW)lParam);
11863 
11864   case WM_CREATE:
11865     return LISTVIEW_Create(hwnd, (LPCREATESTRUCTW)lParam);
11866 
11867   case WM_DESTROY:
11868     return LISTVIEW_Destroy(infoPtr);
11869 
11870   case WM_ENABLE:
11871     return LISTVIEW_Enable(infoPtr);
11872 
11873   case WM_ERASEBKGND:
11874     return LISTVIEW_EraseBkgnd(infoPtr, (HDC)wParam);
11875 
11876   case WM_GETDLGCODE:
11877     return DLGC_WANTCHARS | DLGC_WANTARROWS;
11878 
11879   case WM_GETFONT:
11880     return (LRESULT)infoPtr->hFont;
11881 
11882   case WM_HSCROLL:
11883     return LISTVIEW_HScroll(infoPtr, (INT)LOWORD(wParam), 0);
11884 
11885   case WM_KEYDOWN:
11886     return LISTVIEW_KeyDown(infoPtr, (INT)wParam, (LONG)lParam);
11887 
11888   case WM_KILLFOCUS:
11889     return LISTVIEW_KillFocus(infoPtr);
11890 
11891   case WM_LBUTTONDBLCLK:
11892     return LISTVIEW_LButtonDblClk(infoPtr, (WORD)wParam, (SHORT)LOWORD(lParam), (SHORT)HIWORD(lParam));
11893 
11894   case WM_LBUTTONDOWN:
11895     return LISTVIEW_LButtonDown(infoPtr, (WORD)wParam, (SHORT)LOWORD(lParam), (SHORT)HIWORD(lParam));
11896 
11897   case WM_LBUTTONUP:
11898     return LISTVIEW_LButtonUp(infoPtr, (WORD)wParam, (SHORT)LOWORD(lParam), (SHORT)HIWORD(lParam));
11899 
11900   case WM_MOUSEMOVE:
11901     return LISTVIEW_MouseMove (infoPtr, (WORD)wParam, (SHORT)LOWORD(lParam), (SHORT)HIWORD(lParam));
11902 
11903   case WM_MOUSEHOVER:
11904     return LISTVIEW_MouseHover(infoPtr, (SHORT)LOWORD(lParam), (SHORT)HIWORD(lParam));
11905 
11906   case WM_NCDESTROY:
11907     return LISTVIEW_NCDestroy(infoPtr);
11908 
11909   case WM_NCPAINT:
11910     return LISTVIEW_NCPaint(infoPtr, (HRGN)wParam);
11911 
11912   case WM_NOTIFY:
11913     return LISTVIEW_Notify(infoPtr, (LPNMHDR)lParam);
11914 
11915   case WM_NOTIFYFORMAT:
11916     return LISTVIEW_NotifyFormat(infoPtr, (HWND)wParam, (INT)lParam);
11917 
11918   case WM_PRINTCLIENT:
11919     return LISTVIEW_PrintClient(infoPtr, (HDC)wParam, (DWORD)lParam);
11920 
11921   case WM_PAINT:
11922     return LISTVIEW_WMPaint(infoPtr, (HDC)wParam);
11923 
11924   case WM_RBUTTONDBLCLK:
11925     return LISTVIEW_RButtonDblClk(infoPtr, (WORD)wParam, (SHORT)LOWORD(lParam), (SHORT)HIWORD(lParam));
11926 
11927   case WM_RBUTTONDOWN:
11928     return LISTVIEW_RButtonDown(infoPtr, (WORD)wParam, (SHORT)LOWORD(lParam), (SHORT)HIWORD(lParam));
11929 
11930   case WM_SETCURSOR:
11931     return LISTVIEW_SetCursor(infoPtr, wParam, lParam);
11932 
11933   case WM_SETFOCUS:
11934     return LISTVIEW_SetFocus(infoPtr, (HWND)wParam);
11935 
11936   case WM_SETFONT:
11937     return LISTVIEW_SetFont(infoPtr, (HFONT)wParam, (WORD)lParam);
11938 
11939   case WM_SETREDRAW:
11940     return LISTVIEW_SetRedraw(infoPtr, (BOOL)wParam);
11941 
11942   case WM_SHOWWINDOW:
11943     return LISTVIEW_ShowWindow(infoPtr, wParam, lParam);
11944 
11945   case WM_STYLECHANGED:
11946     return LISTVIEW_StyleChanged(infoPtr, wParam, (LPSTYLESTRUCT)lParam);
11947 
11948   case WM_STYLECHANGING:
11949     return LISTVIEW_StyleChanging(wParam, (LPSTYLESTRUCT)lParam);
11950 
11951   case WM_SYSCOLORCHANGE:
11952     COMCTL32_RefreshSysColors();
11953 #ifdef __REACTOS__
11954     if (infoPtr->bDefaultBkColor)
11955     {
11956         LISTVIEW_SetBkColor(infoPtr, comctl32_color.clrWindow);
11957         infoPtr->bDefaultBkColor = TRUE;
11958         LISTVIEW_InvalidateList(infoPtr);
11959     }
11960 #endif
11961     return 0;
11962 
11963 /*	case WM_TIMER: */
11964   case WM_THEMECHANGED:
11965     return LISTVIEW_ThemeChanged(infoPtr);
11966 
11967   case WM_VSCROLL:
11968     return LISTVIEW_VScroll(infoPtr, (INT)LOWORD(wParam), 0);
11969 
11970   case WM_MOUSEWHEEL:
11971       if (wParam & (MK_SHIFT | MK_CONTROL))
11972           return DefWindowProcW(hwnd, uMsg, wParam, lParam);
11973       return LISTVIEW_MouseWheel(infoPtr, (short int)HIWORD(wParam));
11974 
11975   case WM_WINDOWPOSCHANGED:
11976       if (!(((WINDOWPOS *)lParam)->flags & SWP_NOSIZE))
11977       {
11978           SetWindowPos(infoPtr->hwndSelf, 0, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOACTIVATE |
11979                        SWP_NOZORDER | SWP_NOMOVE | SWP_NOSIZE);
11980 
11981           if ((infoPtr->dwStyle & LVS_OWNERDRAWFIXED) && (infoPtr->uView == LV_VIEW_DETAILS))
11982           {
11983               if (notify_measureitem(infoPtr)) LISTVIEW_InvalidateList(infoPtr);
11984           }
11985           LISTVIEW_Size(infoPtr, ((WINDOWPOS *)lParam)->cx, ((WINDOWPOS *)lParam)->cy);
11986       }
11987       return DefWindowProcW(hwnd, uMsg, wParam, lParam);
11988 
11989 /*	case WM_WININICHANGE: */
11990 
11991   default:
11992     if ((uMsg >= WM_USER) && (uMsg < WM_APP) && !COMCTL32_IsReflectedMessage(uMsg))
11993       ERR("unknown msg %04x wp=%08lx lp=%08lx\n", uMsg, wParam, lParam);
11994 
11995     return DefWindowProcW(hwnd, uMsg, wParam, lParam);
11996   }
11997 
11998 }
11999 
12000 /***
12001  * DESCRIPTION:
12002  * Registers the window class.
12003  *
12004  * PARAMETER(S):
12005  * None
12006  *
12007  * RETURN:
12008  * None
12009  */
12010 void LISTVIEW_Register(void)
12011 {
12012     WNDCLASSW wndClass;
12013 
12014     ZeroMemory(&wndClass, sizeof(WNDCLASSW));
12015     wndClass.style = CS_GLOBALCLASS | CS_DBLCLKS;
12016     wndClass.lpfnWndProc = LISTVIEW_WindowProc;
12017     wndClass.cbClsExtra = 0;
12018     wndClass.cbWndExtra = sizeof(LISTVIEW_INFO *);
12019     wndClass.hCursor = LoadCursorW(0, (LPWSTR)IDC_ARROW);
12020     wndClass.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
12021     wndClass.lpszClassName = WC_LISTVIEWW;
12022     RegisterClassW(&wndClass);
12023 }
12024 
12025 /***
12026  * DESCRIPTION:
12027  * Unregisters the window class.
12028  *
12029  * PARAMETER(S):
12030  * None
12031  *
12032  * RETURN:
12033  * None
12034  */
12035 void LISTVIEW_Unregister(void)
12036 {
12037     UnregisterClassW(WC_LISTVIEWW, NULL);
12038 }
12039 
12040 /***
12041  * DESCRIPTION:
12042  * Handle any WM_COMMAND messages
12043  *
12044  * PARAMETER(S):
12045  * [I] infoPtr : valid pointer to the listview structure
12046  * [I] wParam : the first message parameter
12047  * [I] lParam : the second message parameter
12048  *
12049  * RETURN:
12050  *   Zero.
12051  */
12052 static LRESULT LISTVIEW_Command(LISTVIEW_INFO *infoPtr, WPARAM wParam, LPARAM lParam)
12053 {
12054 
12055     TRACE("(%p %x %x %lx)\n", infoPtr, HIWORD(wParam), LOWORD(wParam), lParam);
12056 
12057     if (!infoPtr->hwndEdit) return 0;
12058 
12059     switch (HIWORD(wParam))
12060     {
12061 	case EN_UPDATE:
12062 	{
12063 	    /*
12064 	     * Adjust the edit window size
12065 	     */
12066 	    WCHAR buffer[1024];
12067 	    HDC           hdc = GetDC(infoPtr->hwndEdit);
12068             HFONT         hFont, hOldFont = 0;
12069 	    RECT	  rect;
12070 	    SIZE	  sz;
12071 
12072 	    if (!infoPtr->hwndEdit || !hdc) return 0;
12073 	    GetWindowTextW(infoPtr->hwndEdit, buffer, ARRAY_SIZE(buffer));
12074 	    GetWindowRect(infoPtr->hwndEdit, &rect);
12075 
12076             /* Select font to get the right dimension of the string */
12077             hFont = (HFONT)SendMessageW(infoPtr->hwndEdit, WM_GETFONT, 0, 0);
12078             if (hFont)
12079             {
12080                 hOldFont = SelectObject(hdc, hFont);
12081             }
12082 
12083 	    if (GetTextExtentPoint32W(hdc, buffer, lstrlenW(buffer), &sz))
12084 	    {
12085                 TEXTMETRICW textMetric;
12086 
12087                 /* Add Extra spacing for the next character */
12088                 GetTextMetricsW(hdc, &textMetric);
12089                 sz.cx += (textMetric.tmMaxCharWidth * 2);
12090 
12091 		SetWindowPos(infoPtr->hwndEdit, NULL, 0, 0, sz.cx,
12092 		    rect.bottom - rect.top, SWP_DRAWFRAME | SWP_NOMOVE | SWP_NOZORDER);
12093 	    }
12094             if (hFont)
12095                 SelectObject(hdc, hOldFont);
12096 
12097 	    ReleaseDC(infoPtr->hwndEdit, hdc);
12098 
12099 	    break;
12100 	}
12101 	case EN_KILLFOCUS:
12102 	{
12103             if (infoPtr->notify_mask & NOTIFY_MASK_END_LABEL_EDIT)
12104                 LISTVIEW_CancelEditLabel(infoPtr);
12105             break;
12106 	}
12107 
12108 	default:
12109 	  return SendMessageW (infoPtr->hwndNotify, WM_COMMAND, wParam, lParam);
12110     }
12111 
12112     return 0;
12113 }
12114