xref: /reactos/dll/win32/comctl32/listview.c (revision b5218987)
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     INT nCountPerRow;
7453     INT i;
7454 
7455     TRACE("nItem=%d, uFlags=%x, nItemCount=%d\n", nItem, uFlags, infoPtr->nItemCount);
7456     if (nItem < -1 || nItem >= infoPtr->nItemCount) return -1;
7457 
7458     ZeroMemory(&lvFindInfo, sizeof(lvFindInfo));
7459 
7460     if (uFlags & LVNI_CUT)
7461       uMask |= LVIS_CUT;
7462 
7463     if (uFlags & LVNI_DROPHILITED)
7464       uMask |= LVIS_DROPHILITED;
7465 
7466     if (uFlags & LVNI_FOCUSED)
7467       uMask |= LVIS_FOCUSED;
7468 
7469     if (uFlags & LVNI_SELECTED)
7470       uMask |= LVIS_SELECTED;
7471 
7472     /* if we're asked for the focused item, that's only one,
7473      * so it's worth optimizing */
7474     if (uFlags & LVNI_FOCUSED)
7475     {
7476 	if ((LISTVIEW_GetItemState(infoPtr, infoPtr->nFocusedItem, uMask) & uMask) != uMask) return -1;
7477 	return (infoPtr->nFocusedItem == nItem) ? -1 : infoPtr->nFocusedItem;
7478     }
7479 
7480     if (uFlags & LVNI_ABOVE)
7481     {
7482       if ((infoPtr->uView == LV_VIEW_LIST) || (infoPtr->uView == LV_VIEW_DETAILS))
7483       {
7484         while (nItem >= 0)
7485         {
7486           nItem--;
7487           if ((LISTVIEW_GetItemState(infoPtr, nItem, uMask) & uMask) == uMask)
7488             return nItem;
7489         }
7490       }
7491       else
7492       {
7493         /* Special case for autoarrange - move 'til the top of a list */
7494         if (is_autoarrange(infoPtr))
7495         {
7496           nCountPerRow = LISTVIEW_GetCountPerRow(infoPtr);
7497           while (nItem - nCountPerRow >= 0)
7498           {
7499             nItem -= nCountPerRow;
7500             if ((LISTVIEW_GetItemState(infoPtr, nItem, uMask) & uMask) == uMask)
7501               return nItem;
7502           }
7503           return -1;
7504         }
7505         lvFindInfo.flags = LVFI_NEARESTXY;
7506         lvFindInfo.vkDirection = VK_UP;
7507         LISTVIEW_GetItemPosition(infoPtr, nItem, &lvFindInfo.pt);
7508         while ((nItem = LISTVIEW_FindItemW(infoPtr, nItem, &lvFindInfo)) != -1)
7509         {
7510           if ((LISTVIEW_GetItemState(infoPtr, nItem, uMask) & uMask) == uMask)
7511             return nItem;
7512         }
7513       }
7514     }
7515     else if (uFlags & LVNI_BELOW)
7516     {
7517       if ((infoPtr->uView == LV_VIEW_LIST) || (infoPtr->uView == LV_VIEW_DETAILS))
7518       {
7519         while (nItem < infoPtr->nItemCount)
7520         {
7521           nItem++;
7522           if ((LISTVIEW_GetItemState(infoPtr, nItem, uMask) & uMask) == uMask)
7523             return nItem;
7524         }
7525       }
7526       else
7527       {
7528         /* Special case for autoarrange - move 'til the bottom of a list */
7529         if (is_autoarrange(infoPtr))
7530         {
7531           nCountPerRow = LISTVIEW_GetCountPerRow(infoPtr);
7532           while (nItem + nCountPerRow < infoPtr->nItemCount )
7533           {
7534             nItem += nCountPerRow;
7535             if ((LISTVIEW_GetItemState(infoPtr, nItem, uMask) & uMask) == uMask)
7536               return nItem;
7537           }
7538           return -1;
7539         }
7540         lvFindInfo.flags = LVFI_NEARESTXY;
7541         lvFindInfo.vkDirection = VK_DOWN;
7542         LISTVIEW_GetItemPosition(infoPtr, nItem, &lvFindInfo.pt);
7543         while ((nItem = LISTVIEW_FindItemW(infoPtr, nItem, &lvFindInfo)) != -1)
7544         {
7545           if ((LISTVIEW_GetItemState(infoPtr, nItem, uMask) & uMask) == uMask)
7546             return nItem;
7547         }
7548       }
7549     }
7550     else if (uFlags & LVNI_TOLEFT)
7551     {
7552       if (infoPtr->uView == LV_VIEW_LIST)
7553       {
7554         nCountPerColumn = LISTVIEW_GetCountPerColumn(infoPtr);
7555         while (nItem - nCountPerColumn >= 0)
7556         {
7557           nItem -= nCountPerColumn;
7558           if ((LISTVIEW_GetItemState(infoPtr, nItem, uMask) & uMask) == uMask)
7559             return nItem;
7560         }
7561       }
7562       else if ((infoPtr->uView == LV_VIEW_SMALLICON) || (infoPtr->uView == LV_VIEW_ICON))
7563       {
7564         /* Special case for autoarrange - move 'til the beginning of a row */
7565         if (is_autoarrange(infoPtr))
7566         {
7567           nCountPerRow = LISTVIEW_GetCountPerRow(infoPtr);
7568           while (nItem % nCountPerRow > 0)
7569           {
7570             nItem --;
7571             if ((LISTVIEW_GetItemState(infoPtr, nItem, uMask) & uMask) == uMask)
7572               return nItem;
7573           }
7574           return -1;
7575         }
7576         lvFindInfo.flags = LVFI_NEARESTXY;
7577         lvFindInfo.vkDirection = VK_LEFT;
7578         LISTVIEW_GetItemPosition(infoPtr, nItem, &lvFindInfo.pt);
7579         while ((nItem = LISTVIEW_FindItemW(infoPtr, nItem, &lvFindInfo)) != -1)
7580         {
7581           if ((LISTVIEW_GetItemState(infoPtr, nItem, uMask) & uMask) == uMask)
7582             return nItem;
7583         }
7584       }
7585     }
7586     else if (uFlags & LVNI_TORIGHT)
7587     {
7588       if (infoPtr->uView == LV_VIEW_LIST)
7589       {
7590         nCountPerColumn = LISTVIEW_GetCountPerColumn(infoPtr);
7591         while (nItem + nCountPerColumn < infoPtr->nItemCount)
7592         {
7593           nItem += nCountPerColumn;
7594           if ((LISTVIEW_GetItemState(infoPtr, nItem, uMask) & uMask) == uMask)
7595             return nItem;
7596         }
7597       }
7598       else if ((infoPtr->uView == LV_VIEW_SMALLICON) || (infoPtr->uView == LV_VIEW_ICON))
7599       {
7600         /* Special case for autoarrange - move 'til the end of a row */
7601         if (is_autoarrange(infoPtr))
7602         {
7603           nCountPerRow = LISTVIEW_GetCountPerRow(infoPtr);
7604           while (nItem % nCountPerRow < nCountPerRow - 1 )
7605           {
7606             nItem ++;
7607             if ((LISTVIEW_GetItemState(infoPtr, nItem, uMask) & uMask) == uMask)
7608               return nItem;
7609           }
7610           return -1;
7611         }
7612         lvFindInfo.flags = LVFI_NEARESTXY;
7613         lvFindInfo.vkDirection = VK_RIGHT;
7614         LISTVIEW_GetItemPosition(infoPtr, nItem, &lvFindInfo.pt);
7615         while ((nItem = LISTVIEW_FindItemW(infoPtr, nItem, &lvFindInfo)) != -1)
7616         {
7617           if ((LISTVIEW_GetItemState(infoPtr, nItem, uMask) & uMask) == uMask)
7618             return nItem;
7619         }
7620       }
7621     }
7622     else
7623     {
7624       nItem++;
7625 
7626       /* search by index */
7627       for (i = nItem; i < infoPtr->nItemCount; i++)
7628       {
7629         if ((LISTVIEW_GetItemState(infoPtr, i, uMask) & uMask) == uMask)
7630           return i;
7631       }
7632     }
7633 
7634     return -1;
7635 }
7636 
7637 /* LISTVIEW_GetNumberOfWorkAreas */
7638 
7639 /***
7640  * DESCRIPTION:
7641  * Retrieves the origin coordinates when in icon or small icon display mode.
7642  *
7643  * PARAMETER(S):
7644  * [I] infoPtr : valid pointer to the listview structure
7645  * [O] lpptOrigin : coordinate information
7646  *
7647  * RETURN:
7648  *   None.
7649  */
7650 static void LISTVIEW_GetOrigin(const LISTVIEW_INFO *infoPtr, LPPOINT lpptOrigin)
7651 {
7652     INT nHorzPos = 0, nVertPos = 0;
7653     SCROLLINFO scrollInfo;
7654 
7655     scrollInfo.cbSize = sizeof(SCROLLINFO);
7656     scrollInfo.fMask = SIF_POS;
7657 
7658     if (GetScrollInfo(infoPtr->hwndSelf, SB_HORZ, &scrollInfo))
7659 	nHorzPos = scrollInfo.nPos;
7660     if (GetScrollInfo(infoPtr->hwndSelf, SB_VERT, &scrollInfo))
7661 	nVertPos = scrollInfo.nPos;
7662 
7663     TRACE("nHorzPos=%d, nVertPos=%d\n", nHorzPos, nVertPos);
7664 
7665     lpptOrigin->x = infoPtr->rcList.left;
7666     lpptOrigin->y = infoPtr->rcList.top;
7667     if (infoPtr->uView == LV_VIEW_LIST)
7668 	nHorzPos *= infoPtr->nItemWidth;
7669     else if (infoPtr->uView == LV_VIEW_DETAILS)
7670 	nVertPos *= infoPtr->nItemHeight;
7671 
7672     lpptOrigin->x -= nHorzPos;
7673     lpptOrigin->y -= nVertPos;
7674 
7675     TRACE(" origin=%s\n", wine_dbgstr_point(lpptOrigin));
7676 }
7677 
7678 /***
7679  * DESCRIPTION:
7680  * Retrieves the width of a string.
7681  *
7682  * PARAMETER(S):
7683  * [I] hwnd : window handle
7684  * [I] lpszText : text string to process
7685  * [I] isW : TRUE if lpszText is Unicode, FALSE otherwise
7686  *
7687  * RETURN:
7688  *   SUCCESS : string width (in pixels)
7689  *   FAILURE : zero
7690  */
7691 static INT LISTVIEW_GetStringWidthT(const LISTVIEW_INFO *infoPtr, LPCWSTR lpszText, BOOL isW)
7692 {
7693     SIZE stringSize;
7694 
7695     stringSize.cx = 0;
7696     if (is_text(lpszText))
7697     {
7698     	HFONT hFont = infoPtr->hFont ? infoPtr->hFont : infoPtr->hDefaultFont;
7699     	HDC hdc = GetDC(infoPtr->hwndSelf);
7700     	HFONT hOldFont = SelectObject(hdc, hFont);
7701 
7702     	if (isW)
7703   	    GetTextExtentPointW(hdc, lpszText, lstrlenW(lpszText), &stringSize);
7704     	else
7705   	    GetTextExtentPointA(hdc, (LPCSTR)lpszText, lstrlenA((LPCSTR)lpszText), &stringSize);
7706     	SelectObject(hdc, hOldFont);
7707     	ReleaseDC(infoPtr->hwndSelf, hdc);
7708     }
7709     return stringSize.cx;
7710 }
7711 
7712 /***
7713  * DESCRIPTION:
7714  * Determines which listview item is located at the specified position.
7715  *
7716  * PARAMETER(S):
7717  * [I] infoPtr : valid pointer to the listview structure
7718  * [IO] lpht : hit test information
7719  * [I] subitem : fill out iSubItem.
7720  * [I] select : return the index only if the hit selects the item
7721  *
7722  * NOTE:
7723  * (mm 20001022): We must not allow iSubItem to be touched, for
7724  * an app might pass only a structure with space up to iItem!
7725  * (MS Office 97 does that for instance in the file open dialog)
7726  *
7727  * RETURN:
7728  *   SUCCESS : item index
7729  *   FAILURE : -1
7730  */
7731 static INT LISTVIEW_HitTest(const LISTVIEW_INFO *infoPtr, LPLVHITTESTINFO lpht, BOOL subitem, BOOL select)
7732 {
7733     WCHAR szDispText[DISP_TEXT_SIZE] = { '\0' };
7734     RECT rcBox, rcBounds, rcState, rcIcon, rcLabel, rcSearch;
7735     POINT Origin, Position, opt;
7736     BOOL is_fullrow;
7737     LVITEMW lvItem;
7738     ITERATOR i;
7739     INT iItem;
7740 
7741     TRACE("(pt=%s, subitem=%d, select=%d)\n", wine_dbgstr_point(&lpht->pt), subitem, select);
7742 
7743     lpht->flags = 0;
7744     lpht->iItem = -1;
7745     if (subitem) lpht->iSubItem = 0;
7746 
7747     LISTVIEW_GetOrigin(infoPtr, &Origin);
7748 
7749     /* set whole list relation flags */
7750     if (subitem && infoPtr->uView == LV_VIEW_DETAILS)
7751     {
7752         /* LVM_SUBITEMHITTEST checks left bound of possible client area */
7753         if (infoPtr->rcList.left > lpht->pt.x && Origin.x < lpht->pt.x)
7754 	    lpht->flags |= LVHT_TOLEFT;
7755 
7756 	if (lpht->pt.y < infoPtr->rcList.top && lpht->pt.y >= 0)
7757 	    opt.y = lpht->pt.y + infoPtr->rcList.top;
7758 	else
7759 	    opt.y = lpht->pt.y;
7760 
7761 	if (infoPtr->rcList.bottom < opt.y)
7762 	    lpht->flags |= LVHT_BELOW;
7763     }
7764     else
7765     {
7766 	if (infoPtr->rcList.left > lpht->pt.x)
7767 	    lpht->flags |= LVHT_TOLEFT;
7768 	else if (infoPtr->rcList.right < lpht->pt.x)
7769 	    lpht->flags |= LVHT_TORIGHT;
7770 
7771 	if (infoPtr->rcList.top > lpht->pt.y)
7772 	    lpht->flags |= LVHT_ABOVE;
7773 	else if (infoPtr->rcList.bottom < lpht->pt.y)
7774 	    lpht->flags |= LVHT_BELOW;
7775     }
7776 
7777     /* even if item is invalid try to find subitem */
7778     if (infoPtr->uView == LV_VIEW_DETAILS && subitem)
7779     {
7780 	RECT *pRect;
7781 	INT j;
7782 
7783 	opt.x = lpht->pt.x - Origin.x;
7784 
7785 	lpht->iSubItem = -1;
7786 	for (j = 0; j < DPA_GetPtrCount(infoPtr->hdpaColumns); j++)
7787 	{
7788 	    pRect = &LISTVIEW_GetColumnInfo(infoPtr, j)->rcHeader;
7789 
7790 	    if ((opt.x >= pRect->left) && (opt.x < pRect->right))
7791 	    {
7792 		lpht->iSubItem = j;
7793 		break;
7794 	    }
7795 	}
7796 	TRACE("lpht->iSubItem=%d\n", lpht->iSubItem);
7797 
7798 	/* if we're outside horizontal columns bounds there's nothing to test further */
7799 	if (lpht->iSubItem == -1)
7800 	{
7801 	    lpht->iItem = -1;
7802 	    lpht->flags = LVHT_NOWHERE;
7803 	    return -1;
7804 	}
7805     }
7806 
7807     TRACE("lpht->flags=0x%x\n", lpht->flags);
7808     if (lpht->flags) return -1;
7809 
7810     lpht->flags |= LVHT_NOWHERE;
7811 
7812     /* first deal with the large items */
7813     rcSearch.left = lpht->pt.x;
7814     rcSearch.top = lpht->pt.y;
7815     rcSearch.right = rcSearch.left + 1;
7816     rcSearch.bottom = rcSearch.top + 1;
7817 
7818     iterator_frameditems(&i, infoPtr, &rcSearch);
7819     iterator_next(&i); /* go to first item in the sequence */
7820     iItem = i.nItem;
7821     iterator_destroy(&i);
7822 
7823     TRACE("lpht->iItem=%d\n", iItem);
7824     if (iItem == -1) return -1;
7825 
7826     lvItem.mask = LVIF_STATE | LVIF_TEXT;
7827     if (infoPtr->uView == LV_VIEW_DETAILS) lvItem.mask |= LVIF_INDENT;
7828     lvItem.stateMask = LVIS_STATEIMAGEMASK;
7829     if (infoPtr->uView == LV_VIEW_ICON) lvItem.stateMask |= LVIS_FOCUSED;
7830     lvItem.iItem = iItem;
7831     lvItem.iSubItem = subitem ? lpht->iSubItem : 0;
7832     lvItem.pszText = szDispText;
7833     lvItem.cchTextMax = DISP_TEXT_SIZE;
7834     if (!LISTVIEW_GetItemW(infoPtr, &lvItem)) return -1;
7835     if (!infoPtr->bFocus) lvItem.state &= ~LVIS_FOCUSED;
7836 
7837     LISTVIEW_GetItemMetrics(infoPtr, &lvItem, &rcBox, NULL, &rcIcon, &rcState, &rcLabel);
7838     LISTVIEW_GetItemOrigin(infoPtr, iItem, &Position);
7839     opt.x = lpht->pt.x - Position.x - Origin.x;
7840 
7841     if (lpht->pt.y < infoPtr->rcList.top && lpht->pt.y >= 0)
7842 	opt.y = lpht->pt.y - Position.y - Origin.y + infoPtr->rcList.top;
7843     else
7844 	opt.y = lpht->pt.y - Position.y - Origin.y;
7845 
7846     if (infoPtr->uView == LV_VIEW_DETAILS)
7847     {
7848 	rcBounds = rcBox;
7849 	if (infoPtr->dwLvExStyle & LVS_EX_FULLROWSELECT)
7850 	    opt.x = lpht->pt.x - Origin.x;
7851     }
7852     else
7853     {
7854         UnionRect(&rcBounds, &rcIcon, &rcLabel);
7855         UnionRect(&rcBounds, &rcBounds, &rcState);
7856     }
7857     TRACE("rcBounds=%s\n", wine_dbgstr_rect(&rcBounds));
7858     if (!PtInRect(&rcBounds, opt)) return -1;
7859 
7860     /* That's a special case - row rectangle is used as item rectangle and
7861        returned flags contain all item parts. */
7862     is_fullrow = (infoPtr->uView == LV_VIEW_DETAILS) && ((infoPtr->dwLvExStyle & LVS_EX_FULLROWSELECT) || (infoPtr->dwStyle & LVS_OWNERDRAWFIXED));
7863 
7864     if (PtInRect(&rcIcon, opt))
7865 	lpht->flags |= LVHT_ONITEMICON;
7866     else if (PtInRect(&rcLabel, opt))
7867 	lpht->flags |= LVHT_ONITEMLABEL;
7868     else if (infoPtr->himlState && PtInRect(&rcState, opt))
7869 	lpht->flags |= LVHT_ONITEMSTATEICON;
7870     if (is_fullrow && !(lpht->flags & LVHT_ONITEM))
7871     {
7872 	lpht->flags = LVHT_ONITEM | LVHT_ABOVE;
7873     }
7874     if (lpht->flags & LVHT_ONITEM)
7875 	lpht->flags &= ~LVHT_NOWHERE;
7876     TRACE("lpht->flags=0x%x\n", lpht->flags);
7877 
7878     if (select && !is_fullrow)
7879     {
7880         if (infoPtr->uView == LV_VIEW_DETAILS)
7881         {
7882             /* get main item bounds */
7883             lvItem.iSubItem = 0;
7884             LISTVIEW_GetItemMetrics(infoPtr, &lvItem, &rcBox, NULL, &rcIcon, &rcState, &rcLabel);
7885             UnionRect(&rcBounds, &rcIcon, &rcLabel);
7886             UnionRect(&rcBounds, &rcBounds, &rcState);
7887         }
7888         if (!PtInRect(&rcBounds, opt)) iItem = -1;
7889     }
7890     return lpht->iItem = iItem;
7891 }
7892 
7893 /***
7894  * DESCRIPTION:
7895  * Inserts a new item in the listview control.
7896  *
7897  * PARAMETER(S):
7898  * [I] infoPtr : valid pointer to the listview structure
7899  * [I] lpLVItem : item information
7900  * [I] isW : TRUE if lpLVItem is Unicode, FALSE if it's ANSI
7901  *
7902  * RETURN:
7903  *   SUCCESS : new item index
7904  *   FAILURE : -1
7905  */
7906 static INT LISTVIEW_InsertItemT(LISTVIEW_INFO *infoPtr, const LVITEMW *lpLVItem, BOOL isW)
7907 {
7908     INT nItem;
7909     HDPA hdpaSubItems;
7910     NMLISTVIEW nmlv;
7911     ITEM_INFO *lpItem;
7912     ITEM_ID *lpID;
7913     BOOL is_sorted, has_changed;
7914     LVITEMW item;
7915     HWND hwndSelf = infoPtr->hwndSelf;
7916 
7917     TRACE("(item=%s, isW=%d)\n", debuglvitem_t(lpLVItem, isW), isW);
7918 
7919     if (infoPtr->dwStyle & LVS_OWNERDATA) return infoPtr->nItemCount++;
7920 
7921     /* make sure it's an item, and not a subitem; cannot insert a subitem */
7922     if (!lpLVItem || lpLVItem->iSubItem) return -1;
7923 
7924     if (!is_assignable_item(lpLVItem, infoPtr->dwStyle)) return -1;
7925 
7926     if (!(lpItem = Alloc(sizeof(ITEM_INFO)))) return -1;
7927 
7928     /* insert item in listview control data structure */
7929     if ( !(hdpaSubItems = DPA_Create(8)) ) goto fail;
7930     if ( !DPA_SetPtr(hdpaSubItems, 0, lpItem) ) assert (FALSE);
7931 
7932     /* link with id struct */
7933     if (!(lpID = Alloc(sizeof(ITEM_ID)))) goto fail;
7934     lpItem->id = lpID;
7935     lpID->item = hdpaSubItems;
7936     lpID->id = get_next_itemid(infoPtr);
7937     if ( DPA_InsertPtr(infoPtr->hdpaItemIds, infoPtr->nItemCount, lpID) == -1) goto fail;
7938 
7939     is_sorted = (infoPtr->dwStyle & (LVS_SORTASCENDING | LVS_SORTDESCENDING)) &&
7940 	        !(infoPtr->dwStyle & LVS_OWNERDRAWFIXED) && (LPSTR_TEXTCALLBACKW != lpLVItem->pszText);
7941 
7942     if (lpLVItem->iItem < 0 && !is_sorted) return -1;
7943 
7944     /* calculate new item index */
7945     if (is_sorted)
7946     {
7947         HDPA hItem;
7948         ITEM_INFO *item_s;
7949         INT i = 0, cmpv;
7950         WCHAR *textW;
7951 
7952         textW = textdupTtoW(lpLVItem->pszText, isW);
7953 
7954         while (i < infoPtr->nItemCount)
7955         {
7956             hItem  = DPA_GetPtr( infoPtr->hdpaItems, i);
7957             item_s = DPA_GetPtr(hItem, 0);
7958 
7959             cmpv = textcmpWT(item_s->hdr.pszText, textW, TRUE);
7960             if (infoPtr->dwStyle & LVS_SORTDESCENDING) cmpv *= -1;
7961 
7962             if (cmpv >= 0) break;
7963             i++;
7964         }
7965 
7966         textfreeT(textW, isW);
7967 
7968         nItem = i;
7969     }
7970     else
7971         nItem = min(lpLVItem->iItem, infoPtr->nItemCount);
7972 
7973     TRACE("inserting at %d, sorted=%d, count=%d, iItem=%d\n", nItem, is_sorted, infoPtr->nItemCount, lpLVItem->iItem);
7974     nItem = DPA_InsertPtr( infoPtr->hdpaItems, nItem, hdpaSubItems );
7975     if (nItem == -1) goto fail;
7976     infoPtr->nItemCount++;
7977 
7978     /* shift indices first so they don't get tangled */
7979     LISTVIEW_ShiftIndices(infoPtr, nItem, 1);
7980 
7981     /* set the item attributes */
7982     if (lpLVItem->mask & (LVIF_GROUPID|LVIF_COLUMNS))
7983     {
7984         /* full size structure expected - _WIN32IE >= 0x560 */
7985         item = *lpLVItem;
7986     }
7987     else if (lpLVItem->mask & LVIF_INDENT)
7988     {
7989         /* indent member expected - _WIN32IE >= 0x300 */
7990         memcpy(&item, lpLVItem, offsetof( LVITEMW, iGroupId ));
7991     }
7992     else
7993     {
7994         /* minimal structure expected */
7995         memcpy(&item, lpLVItem, offsetof( LVITEMW, iIndent ));
7996     }
7997     item.iItem = nItem;
7998     if (infoPtr->dwLvExStyle & LVS_EX_CHECKBOXES)
7999     {
8000         if (item.mask & LVIF_STATE)
8001         {
8002             item.stateMask |= LVIS_STATEIMAGEMASK;
8003             item.state &= ~LVIS_STATEIMAGEMASK;
8004             item.state |= INDEXTOSTATEIMAGEMASK(1);
8005         }
8006         else
8007         {
8008             item.mask |= LVIF_STATE;
8009             item.stateMask = LVIS_STATEIMAGEMASK;
8010             item.state = INDEXTOSTATEIMAGEMASK(1);
8011         }
8012     }
8013 
8014     if (!set_main_item(infoPtr, &item, TRUE, isW, &has_changed)) goto undo;
8015 
8016     /* make room for the position, if we are in the right mode */
8017     if ((infoPtr->uView == LV_VIEW_SMALLICON) || (infoPtr->uView == LV_VIEW_ICON))
8018     {
8019         if (DPA_InsertPtr(infoPtr->hdpaPosX, nItem, 0) == -1)
8020 	    goto undo;
8021         if (DPA_InsertPtr(infoPtr->hdpaPosY, nItem, 0) == -1)
8022 	{
8023 	    DPA_DeletePtr(infoPtr->hdpaPosX, nItem);
8024 	    goto undo;
8025 	}
8026     }
8027 
8028     /* send LVN_INSERTITEM notification */
8029     memset(&nmlv, 0, sizeof(NMLISTVIEW));
8030     nmlv.iItem = nItem;
8031     nmlv.lParam = lpItem->lParam;
8032     notify_listview(infoPtr, LVN_INSERTITEM, &nmlv);
8033     if (!IsWindow(hwndSelf))
8034 	return -1;
8035 
8036     /* align items (set position of each item) */
8037     if (infoPtr->uView == LV_VIEW_SMALLICON || infoPtr->uView == LV_VIEW_ICON)
8038     {
8039 	POINT pt;
8040 
8041 #ifdef __REACTOS__
8042 	if (infoPtr->dwStyle & LVS_ALIGNLEFT)
8043 	    LISTVIEW_NextIconPosLeft(infoPtr, &pt, nItem);
8044         else
8045 	    LISTVIEW_NextIconPosTop(infoPtr, &pt, nItem);
8046 #else
8047     if (infoPtr->dwStyle & LVS_ALIGNLEFT)
8048 	    LISTVIEW_NextIconPosLeft(infoPtr, &pt);
8049         else
8050 	    LISTVIEW_NextIconPosTop(infoPtr, &pt);
8051 #endif
8052 
8053 	LISTVIEW_MoveIconTo(infoPtr, nItem, &pt, TRUE);
8054     }
8055 
8056     /* now is the invalidation fun */
8057     LISTVIEW_ScrollOnInsert(infoPtr, nItem, 1);
8058     return nItem;
8059 
8060 undo:
8061     LISTVIEW_ShiftIndices(infoPtr, nItem, -1);
8062     LISTVIEW_ShiftFocus(infoPtr, infoPtr->nFocusedItem, nItem, -1);
8063     DPA_DeletePtr(infoPtr->hdpaItems, nItem);
8064     infoPtr->nItemCount--;
8065 fail:
8066     DPA_DeletePtr(hdpaSubItems, 0);
8067     DPA_Destroy (hdpaSubItems);
8068     Free (lpItem);
8069     return -1;
8070 }
8071 
8072 /***
8073  * DESCRIPTION:
8074  * Checks item visibility.
8075  *
8076  * PARAMETER(S):
8077  * [I] infoPtr : valid pointer to the listview structure
8078  * [I] nFirst : item index to check for
8079  *
8080  * RETURN:
8081  *   Item visible : TRUE
8082  *   Item invisible or failure : FALSE
8083  */
8084 static BOOL LISTVIEW_IsItemVisible(const LISTVIEW_INFO *infoPtr, INT nItem)
8085 {
8086     POINT Origin, Position;
8087     RECT rcItem;
8088     HDC hdc;
8089     BOOL ret;
8090 
8091     TRACE("nItem=%d\n", nItem);
8092 
8093     if (nItem < 0 || nItem >= DPA_GetPtrCount(infoPtr->hdpaItems)) return FALSE;
8094 
8095     LISTVIEW_GetOrigin(infoPtr, &Origin);
8096     LISTVIEW_GetItemOrigin(infoPtr, nItem, &Position);
8097     rcItem.left = Position.x + Origin.x;
8098     rcItem.top  = Position.y + Origin.y;
8099     rcItem.right  = rcItem.left + infoPtr->nItemWidth;
8100     rcItem.bottom = rcItem.top + infoPtr->nItemHeight;
8101 
8102     hdc = GetDC(infoPtr->hwndSelf);
8103     if (!hdc) return FALSE;
8104     ret = RectVisible(hdc, &rcItem);
8105     ReleaseDC(infoPtr->hwndSelf, hdc);
8106 
8107     return ret;
8108 }
8109 
8110 /***
8111  * DESCRIPTION:
8112  * Redraws a range of items.
8113  *
8114  * PARAMETER(S):
8115  * [I] infoPtr : valid pointer to the listview structure
8116  * [I] nFirst : first item
8117  * [I] nLast : last item
8118  *
8119  * RETURN:
8120  *   SUCCESS : TRUE
8121  *   FAILURE : FALSE
8122  */
8123 static BOOL LISTVIEW_RedrawItems(const LISTVIEW_INFO *infoPtr, INT nFirst, INT nLast)
8124 {
8125     INT i;
8126 
8127     for (i = max(nFirst, 0); i <= min(nLast, infoPtr->nItemCount - 1); i++)
8128 	LISTVIEW_InvalidateItem(infoPtr, i);
8129 
8130     return TRUE;
8131 }
8132 
8133 /***
8134  * DESCRIPTION:
8135  * Scroll the content of a listview.
8136  *
8137  * PARAMETER(S):
8138  * [I] infoPtr : valid pointer to the listview structure
8139  * [I] dx : horizontal scroll amount in pixels
8140  * [I] dy : vertical scroll amount in pixels
8141  *
8142  * RETURN:
8143  *   SUCCESS : TRUE
8144  *   FAILURE : FALSE
8145  *
8146  * COMMENTS:
8147  *  If the control is in report view (LV_VIEW_DETAILS) the control can
8148  *  be scrolled only in line increments. "dy" will be rounded to the
8149  *  nearest number of pixels that are a whole line. Ex: if line height
8150  *  is 16 and an 8 is passed, the list will be scrolled by 16. If a 7
8151  *  is passed, then the scroll will be 0.  (per MSDN 7/2002)
8152  */
8153 static BOOL LISTVIEW_Scroll(LISTVIEW_INFO *infoPtr, INT dx, INT dy)
8154 {
8155     switch(infoPtr->uView) {
8156     case LV_VIEW_DETAILS:
8157 	dy += (dy < 0 ? -1 : 1) * infoPtr->nItemHeight/2;
8158         dy /= infoPtr->nItemHeight;
8159 	break;
8160     case LV_VIEW_LIST:
8161     	if (dy != 0) return FALSE;
8162 	break;
8163     default: /* icon */
8164 	break;
8165     }
8166 
8167     if (dx != 0) LISTVIEW_HScroll(infoPtr, SB_INTERNAL, dx);
8168     if (dy != 0) LISTVIEW_VScroll(infoPtr, SB_INTERNAL, dy);
8169 
8170     return TRUE;
8171 }
8172 
8173 /***
8174  * DESCRIPTION:
8175  * Sets the background color.
8176  *
8177  * PARAMETER(S):
8178  * [I] infoPtr : valid pointer to the listview structure
8179  * [I] color   : background color
8180  *
8181  * RETURN:
8182  *   SUCCESS : TRUE
8183  *   FAILURE : FALSE
8184  */
8185 static BOOL LISTVIEW_SetBkColor(LISTVIEW_INFO *infoPtr, COLORREF color)
8186 {
8187     TRACE("(color=%x)\n", color);
8188 
8189 #ifdef __REACTOS__
8190     infoPtr->bDefaultBkColor = FALSE;
8191 #endif
8192     if(infoPtr->clrBk != color) {
8193 	if (infoPtr->clrBk != CLR_NONE) DeleteObject(infoPtr->hBkBrush);
8194 	infoPtr->clrBk = color;
8195 	if (color == CLR_NONE)
8196 	    infoPtr->hBkBrush = (HBRUSH)GetClassLongPtrW(infoPtr->hwndSelf, GCLP_HBRBACKGROUND);
8197 	else
8198 	{
8199 	    infoPtr->hBkBrush = CreateSolidBrush(color);
8200 	    infoPtr->dwLvExStyle &= ~LVS_EX_TRANSPARENTBKGND;
8201 	}
8202     }
8203 
8204     return TRUE;
8205 }
8206 
8207 /* LISTVIEW_SetBkImage */
8208 
8209 /*** Helper for {Insert,Set}ColumnT *only* */
8210 static void column_fill_hditem(const LISTVIEW_INFO *infoPtr, HDITEMW *lphdi, INT nColumn,
8211                                const LVCOLUMNW *lpColumn, BOOL isW)
8212 {
8213     if (lpColumn->mask & LVCF_FMT)
8214     {
8215 	/* format member is valid */
8216 	lphdi->mask |= HDI_FORMAT;
8217 
8218 	/* set text alignment (leftmost column must be left-aligned) */
8219         if (nColumn == 0 || (lpColumn->fmt & LVCFMT_JUSTIFYMASK) == LVCFMT_LEFT)
8220             lphdi->fmt |= HDF_LEFT;
8221         else if ((lpColumn->fmt & LVCFMT_JUSTIFYMASK) == LVCFMT_RIGHT)
8222             lphdi->fmt |= HDF_RIGHT;
8223         else if ((lpColumn->fmt & LVCFMT_JUSTIFYMASK) == LVCFMT_CENTER)
8224             lphdi->fmt |= HDF_CENTER;
8225 
8226         if (lpColumn->fmt & LVCFMT_BITMAP_ON_RIGHT)
8227             lphdi->fmt |= HDF_BITMAP_ON_RIGHT;
8228 
8229         if (lpColumn->fmt & LVCFMT_COL_HAS_IMAGES)
8230         {
8231             lphdi->fmt |= HDF_IMAGE;
8232             lphdi->iImage = I_IMAGECALLBACK;
8233         }
8234 
8235         if (lpColumn->fmt & LVCFMT_FIXED_WIDTH)
8236             lphdi->fmt |= HDF_FIXEDWIDTH;
8237     }
8238 
8239     if (lpColumn->mask & LVCF_WIDTH)
8240     {
8241         lphdi->mask |= HDI_WIDTH;
8242         if(lpColumn->cx == LVSCW_AUTOSIZE_USEHEADER)
8243         {
8244             /* make it fill the remainder of the controls width */
8245             RECT rcHeader;
8246             INT item_index;
8247 
8248             for(item_index = 0; item_index < (nColumn - 1); item_index++)
8249 	    {
8250             	LISTVIEW_GetHeaderRect(infoPtr, item_index, &rcHeader);
8251 		lphdi->cxy += rcHeader.right - rcHeader.left;
8252 	    }
8253 
8254             /* retrieve the layout of the header */
8255             GetClientRect(infoPtr->hwndSelf, &rcHeader);
8256             TRACE("start cxy=%d rcHeader=%s\n", lphdi->cxy, wine_dbgstr_rect(&rcHeader));
8257 
8258             lphdi->cxy = (rcHeader.right - rcHeader.left) - lphdi->cxy;
8259         }
8260         else
8261             lphdi->cxy = lpColumn->cx;
8262     }
8263 
8264     if (lpColumn->mask & LVCF_TEXT)
8265     {
8266         lphdi->mask |= HDI_TEXT | HDI_FORMAT;
8267         lphdi->fmt |= HDF_STRING;
8268         lphdi->pszText = lpColumn->pszText;
8269         lphdi->cchTextMax = textlenT(lpColumn->pszText, isW);
8270     }
8271 
8272     if (lpColumn->mask & LVCF_IMAGE)
8273     {
8274         lphdi->mask |= HDI_IMAGE;
8275         lphdi->iImage = lpColumn->iImage;
8276     }
8277 
8278     if (lpColumn->mask & LVCF_ORDER)
8279     {
8280 	lphdi->mask |= HDI_ORDER;
8281 	lphdi->iOrder = lpColumn->iOrder;
8282     }
8283 }
8284 
8285 
8286 /***
8287  * DESCRIPTION:
8288  * Inserts a new column.
8289  *
8290  * PARAMETER(S):
8291  * [I] infoPtr : valid pointer to the listview structure
8292  * [I] nColumn : column index
8293  * [I] lpColumn : column information
8294  * [I] isW : TRUE if lpColumn is Unicode, FALSE otherwise
8295  *
8296  * RETURN:
8297  *   SUCCESS : new column index
8298  *   FAILURE : -1
8299  */
8300 static INT LISTVIEW_InsertColumnT(LISTVIEW_INFO *infoPtr, INT nColumn,
8301                                   const LVCOLUMNW *lpColumn, BOOL isW)
8302 {
8303     COLUMN_INFO *lpColumnInfo;
8304     INT nNewColumn;
8305     HDITEMW hdi;
8306 
8307     TRACE("(nColumn=%d, lpColumn=%s, isW=%d)\n", nColumn, debuglvcolumn_t(lpColumn, isW), isW);
8308 
8309     if (!lpColumn || nColumn < 0) return -1;
8310     nColumn = min(nColumn, DPA_GetPtrCount(infoPtr->hdpaColumns));
8311 
8312     ZeroMemory(&hdi, sizeof(HDITEMW));
8313     column_fill_hditem(infoPtr, &hdi, nColumn, lpColumn, isW);
8314 
8315     /*
8316      * A mask not including LVCF_WIDTH turns into a mask of width, width 10
8317      * (can be seen in SPY) otherwise column never gets added.
8318      */
8319     if (!(lpColumn->mask & LVCF_WIDTH)) {
8320         hdi.mask |= HDI_WIDTH;
8321         hdi.cxy = 10;
8322     }
8323 
8324     /*
8325      * when the iSubItem is available Windows copies it to the header lParam. It seems
8326      * to happen only in LVM_INSERTCOLUMN - not in LVM_SETCOLUMN
8327      */
8328     if (lpColumn->mask & LVCF_SUBITEM)
8329     {
8330         hdi.mask |= HDI_LPARAM;
8331         hdi.lParam = lpColumn->iSubItem;
8332     }
8333 
8334     /* create header if not present */
8335     LISTVIEW_CreateHeader(infoPtr);
8336     if (!(LVS_NOCOLUMNHEADER & infoPtr->dwStyle) &&
8337          (infoPtr->uView == LV_VIEW_DETAILS) && (WS_VISIBLE & infoPtr->dwStyle))
8338     {
8339         ShowWindow(infoPtr->hwndHeader, SW_SHOWNORMAL);
8340     }
8341 
8342     /* insert item in header control */
8343     nNewColumn = SendMessageW(infoPtr->hwndHeader,
8344 		              isW ? HDM_INSERTITEMW : HDM_INSERTITEMA,
8345                               nColumn, (LPARAM)&hdi);
8346     if (nNewColumn == -1) return -1;
8347     if (nNewColumn != nColumn) ERR("nColumn=%d, nNewColumn=%d\n", nColumn, nNewColumn);
8348 
8349     /* create our own column info */
8350     if (!(lpColumnInfo = Alloc(sizeof(COLUMN_INFO)))) goto fail;
8351     if (DPA_InsertPtr(infoPtr->hdpaColumns, nNewColumn, lpColumnInfo) == -1) goto fail;
8352 
8353     if (lpColumn->mask & LVCF_FMT) lpColumnInfo->fmt = lpColumn->fmt;
8354     if (lpColumn->mask & LVCF_MINWIDTH) lpColumnInfo->cxMin = lpColumn->cxMin;
8355     if (!SendMessageW(infoPtr->hwndHeader, HDM_GETITEMRECT, nNewColumn, (LPARAM)&lpColumnInfo->rcHeader))
8356         goto fail;
8357 
8358     /* now we have to actually adjust the data */
8359     if (!(infoPtr->dwStyle & LVS_OWNERDATA) && infoPtr->nItemCount > 0)
8360     {
8361 	SUBITEM_INFO *lpSubItem;
8362 	HDPA hdpaSubItems;
8363 	INT nItem, i;
8364 	LVITEMW item;
8365 	BOOL changed;
8366 
8367 	item.iSubItem = nNewColumn;
8368 	item.mask = LVIF_TEXT | LVIF_IMAGE;
8369 	item.iImage = I_IMAGECALLBACK;
8370 	item.pszText = LPSTR_TEXTCALLBACKW;
8371 
8372 	for (nItem = 0; nItem < infoPtr->nItemCount; nItem++)
8373 	{
8374             hdpaSubItems = DPA_GetPtr(infoPtr->hdpaItems, nItem);
8375 	    for (i = 1; i < DPA_GetPtrCount(hdpaSubItems); i++)
8376 	    {
8377                 lpSubItem = DPA_GetPtr(hdpaSubItems, i);
8378 		if (lpSubItem->iSubItem >= nNewColumn)
8379 		    lpSubItem->iSubItem++;
8380 	    }
8381 
8382 	    /* add new subitem for each item */
8383 	    item.iItem = nItem;
8384 	    set_sub_item(infoPtr, &item, isW, &changed);
8385 	}
8386     }
8387 
8388     /* make space for the new column */
8389     LISTVIEW_ScrollColumns(infoPtr, nNewColumn + 1, lpColumnInfo->rcHeader.right - lpColumnInfo->rcHeader.left);
8390     LISTVIEW_UpdateItemSize(infoPtr);
8391 
8392     return nNewColumn;
8393 
8394 fail:
8395     if (nNewColumn != -1) SendMessageW(infoPtr->hwndHeader, HDM_DELETEITEM, nNewColumn, 0);
8396     if (lpColumnInfo)
8397     {
8398 	DPA_DeletePtr(infoPtr->hdpaColumns, nNewColumn);
8399 	Free(lpColumnInfo);
8400     }
8401     return -1;
8402 }
8403 
8404 /***
8405  * DESCRIPTION:
8406  * Sets the attributes of a header item.
8407  *
8408  * PARAMETER(S):
8409  * [I] infoPtr : valid pointer to the listview structure
8410  * [I] nColumn : column index
8411  * [I] lpColumn : column attributes
8412  * [I] isW: if TRUE, then lpColumn is a LPLVCOLUMNW, else it is a LPLVCOLUMNA
8413  *
8414  * RETURN:
8415  *   SUCCESS : TRUE
8416  *   FAILURE : FALSE
8417  */
8418 static BOOL LISTVIEW_SetColumnT(const LISTVIEW_INFO *infoPtr, INT nColumn,
8419                                 const LVCOLUMNW *lpColumn, BOOL isW)
8420 {
8421     HDITEMW hdi, hdiget;
8422     BOOL bResult;
8423 
8424     TRACE("(nColumn=%d, lpColumn=%s, isW=%d)\n", nColumn, debuglvcolumn_t(lpColumn, isW), isW);
8425 
8426     if (!lpColumn || nColumn < 0 || nColumn >= DPA_GetPtrCount(infoPtr->hdpaColumns)) return FALSE;
8427 
8428     ZeroMemory(&hdi, sizeof(HDITEMW));
8429     if (lpColumn->mask & LVCF_FMT)
8430     {
8431         hdi.mask |= HDI_FORMAT;
8432         hdiget.mask = HDI_FORMAT;
8433         if (SendMessageW(infoPtr->hwndHeader, HDM_GETITEMW, nColumn, (LPARAM)&hdiget))
8434 	    hdi.fmt = hdiget.fmt & HDF_STRING;
8435     }
8436     column_fill_hditem(infoPtr, &hdi, nColumn, lpColumn, isW);
8437 
8438     /* set header item attributes */
8439     bResult = SendMessageW(infoPtr->hwndHeader, isW ? HDM_SETITEMW : HDM_SETITEMA, nColumn, (LPARAM)&hdi);
8440     if (!bResult) return FALSE;
8441 
8442     if (lpColumn->mask & LVCF_FMT)
8443     {
8444 	COLUMN_INFO *lpColumnInfo = LISTVIEW_GetColumnInfo(infoPtr, nColumn);
8445 	INT oldFmt = lpColumnInfo->fmt;
8446 
8447 	lpColumnInfo->fmt = lpColumn->fmt;
8448 	if ((oldFmt ^ lpColumn->fmt) & (LVCFMT_JUSTIFYMASK | LVCFMT_IMAGE))
8449 	{
8450 	    if (infoPtr->uView == LV_VIEW_DETAILS) LISTVIEW_InvalidateColumn(infoPtr, nColumn);
8451 	}
8452     }
8453 
8454     if (lpColumn->mask & LVCF_MINWIDTH)
8455 	LISTVIEW_GetColumnInfo(infoPtr, nColumn)->cxMin = lpColumn->cxMin;
8456 
8457     return TRUE;
8458 }
8459 
8460 /***
8461  * DESCRIPTION:
8462  * Sets the column order array
8463  *
8464  * PARAMETERS:
8465  * [I] infoPtr : valid pointer to the listview structure
8466  * [I] iCount : number of elements in column order array
8467  * [I] lpiArray : pointer to column order array
8468  *
8469  * RETURN:
8470  *   SUCCESS : TRUE
8471  *   FAILURE : FALSE
8472  */
8473 static BOOL LISTVIEW_SetColumnOrderArray(LISTVIEW_INFO *infoPtr, INT iCount, const INT *lpiArray)
8474 {
8475     if (!infoPtr->hwndHeader) return FALSE;
8476     infoPtr->colRectsDirty = TRUE;
8477     return SendMessageW(infoPtr->hwndHeader, HDM_SETORDERARRAY, iCount, (LPARAM)lpiArray);
8478 }
8479 
8480 /***
8481  * DESCRIPTION:
8482  * Sets the width of a column
8483  *
8484  * PARAMETERS:
8485  * [I] infoPtr : valid pointer to the listview structure
8486  * [I] nColumn : column index
8487  * [I] cx : column width
8488  *
8489  * RETURN:
8490  *   SUCCESS : TRUE
8491  *   FAILURE : FALSE
8492  */
8493 static BOOL LISTVIEW_SetColumnWidth(LISTVIEW_INFO *infoPtr, INT nColumn, INT cx)
8494 {
8495     WCHAR szDispText[DISP_TEXT_SIZE] = { 0 };
8496     INT max_cx = 0;
8497     HDITEMW hdi;
8498 
8499     TRACE("(nColumn=%d, cx=%d)\n", nColumn, cx);
8500 
8501     /* set column width only if in report or list mode */
8502     if (infoPtr->uView != LV_VIEW_DETAILS && infoPtr->uView != LV_VIEW_LIST) return FALSE;
8503 
8504     /* take care of invalid cx values - LVSCW_AUTOSIZE_* values are negative,
8505        with _USEHEADER being the lowest */
8506     if (infoPtr->uView == LV_VIEW_DETAILS && cx < LVSCW_AUTOSIZE_USEHEADER) cx = LVSCW_AUTOSIZE;
8507     else if (infoPtr->uView == LV_VIEW_LIST && cx <= 0) return FALSE;
8508 
8509     /* resize all columns if in LV_VIEW_LIST mode */
8510     if(infoPtr->uView == LV_VIEW_LIST)
8511     {
8512 	infoPtr->nItemWidth = cx;
8513 	LISTVIEW_InvalidateList(infoPtr);
8514 	return TRUE;
8515     }
8516 
8517     if (nColumn < 0 || nColumn >= DPA_GetPtrCount(infoPtr->hdpaColumns)) return FALSE;
8518 
8519     if (cx == LVSCW_AUTOSIZE || (cx == LVSCW_AUTOSIZE_USEHEADER && nColumn < DPA_GetPtrCount(infoPtr->hdpaColumns) -1))
8520     {
8521 	INT nLabelWidth;
8522 	LVITEMW lvItem;
8523 
8524 	lvItem.mask = LVIF_TEXT;
8525 	lvItem.iItem = 0;
8526 	lvItem.iSubItem = nColumn;
8527 	lvItem.cchTextMax = DISP_TEXT_SIZE;
8528 	for (; lvItem.iItem < infoPtr->nItemCount; lvItem.iItem++)
8529 	{
8530             lvItem.pszText = szDispText;
8531 	    if (!LISTVIEW_GetItemW(infoPtr, &lvItem)) continue;
8532 	    nLabelWidth = LISTVIEW_GetStringWidthT(infoPtr, lvItem.pszText, TRUE);
8533 	    if (max_cx < nLabelWidth) max_cx = nLabelWidth;
8534 	}
8535 	if (infoPtr->himlSmall && (nColumn == 0 || (LISTVIEW_GetColumnInfo(infoPtr, nColumn)->fmt & LVCFMT_IMAGE)))
8536 	    max_cx += infoPtr->iconSize.cx;
8537 	max_cx += TRAILING_LABEL_PADDING;
8538         if (nColumn == 0 && (infoPtr->dwLvExStyle & LVS_EX_CHECKBOXES))
8539             max_cx += GetSystemMetrics(SM_CXSMICON);
8540     }
8541 
8542     /* autosize based on listview items width */
8543     if(cx == LVSCW_AUTOSIZE)
8544 	cx = max_cx;
8545     else if(cx == LVSCW_AUTOSIZE_USEHEADER)
8546     {
8547 	/* if iCol is the last column make it fill the remainder of the controls width */
8548         if(nColumn == DPA_GetPtrCount(infoPtr->hdpaColumns) - 1)
8549 	{
8550 	    RECT rcHeader;
8551 	    POINT Origin;
8552 
8553 	    LISTVIEW_GetOrigin(infoPtr, &Origin);
8554 	    LISTVIEW_GetHeaderRect(infoPtr, nColumn, &rcHeader);
8555 
8556 	    cx = infoPtr->rcList.right - Origin.x - rcHeader.left;
8557 	}
8558 	else
8559 	{
8560             /* Despite what the MS docs say, if this is not the last
8561                column, then MS resizes the column to the width of the
8562                largest text string in the column, including headers
8563                and items. This is different from LVSCW_AUTOSIZE in that
8564 	       LVSCW_AUTOSIZE ignores the header string length. */
8565 	    cx = 0;
8566 
8567 	    /* retrieve header text */
8568 	    hdi.mask = HDI_TEXT|HDI_FORMAT|HDI_IMAGE|HDI_BITMAP;
8569 	    hdi.cchTextMax = DISP_TEXT_SIZE;
8570 	    hdi.pszText = szDispText;
8571 	    if (SendMessageW(infoPtr->hwndHeader, HDM_GETITEMW, nColumn, (LPARAM)&hdi))
8572 	    {
8573 		HDC hdc = GetDC(infoPtr->hwndSelf);
8574 		HFONT old_font = SelectObject(hdc, (HFONT)SendMessageW(infoPtr->hwndHeader, WM_GETFONT, 0, 0));
8575 		HIMAGELIST himl = (HIMAGELIST)SendMessageW(infoPtr->hwndHeader, HDM_GETIMAGELIST, 0, 0);
8576 		INT bitmap_margin = 0;
8577 		SIZE size;
8578 
8579 		if (GetTextExtentPoint32W(hdc, hdi.pszText, lstrlenW(hdi.pszText), &size))
8580 		    cx = size.cx + TRAILING_HEADER_PADDING;
8581 
8582 		if (hdi.fmt & (HDF_IMAGE|HDF_BITMAP))
8583 		    bitmap_margin = SendMessageW(infoPtr->hwndHeader, HDM_GETBITMAPMARGIN, 0, 0);
8584 
8585 		if ((hdi.fmt & HDF_IMAGE) && himl)
8586 		{
8587 		    INT icon_cx, icon_cy;
8588 
8589 		    if (!ImageList_GetIconSize(himl, &icon_cx, &icon_cy))
8590 		        cx += icon_cx + 2*bitmap_margin;
8591 		}
8592 		else if (hdi.fmt & HDF_BITMAP)
8593 		{
8594 		    BITMAP bmp;
8595 
8596 		    GetObjectW(hdi.hbm, sizeof(BITMAP), &bmp);
8597 		    cx += bmp.bmWidth + 2*bitmap_margin;
8598 		}
8599 
8600 		SelectObject(hdc, old_font);
8601 		ReleaseDC(infoPtr->hwndSelf, hdc);
8602 	    }
8603 	    cx = max (cx, max_cx);
8604 	}
8605     }
8606 
8607     if (cx < 0) return FALSE;
8608 
8609     /* call header to update the column change */
8610     hdi.mask = HDI_WIDTH;
8611     hdi.cxy = max(cx, LISTVIEW_GetColumnInfo(infoPtr, nColumn)->cxMin);
8612     TRACE("hdi.cxy=%d\n", hdi.cxy);
8613     return SendMessageW(infoPtr->hwndHeader, HDM_SETITEMW, nColumn, (LPARAM)&hdi);
8614 }
8615 
8616 /***
8617  * Creates the checkbox imagelist.  Helper for LISTVIEW_SetExtendedListViewStyle
8618  *
8619  */
8620 static HIMAGELIST LISTVIEW_CreateCheckBoxIL(const LISTVIEW_INFO *infoPtr)
8621 {
8622     HDC hdc_wnd, hdc;
8623     HBITMAP hbm_im, hbm_mask, hbm_orig;
8624     RECT rc;
8625     HBRUSH hbr_white = GetStockObject(WHITE_BRUSH);
8626     HBRUSH hbr_black = GetStockObject(BLACK_BRUSH);
8627     HIMAGELIST himl;
8628 
8629     himl = ImageList_Create(GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON),
8630                             ILC_COLOR | ILC_MASK, 2, 2);
8631     hdc_wnd = GetDC(infoPtr->hwndSelf);
8632     hdc = CreateCompatibleDC(hdc_wnd);
8633     hbm_im = CreateCompatibleBitmap(hdc_wnd, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON));
8634     hbm_mask = CreateBitmap(GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), 1, 1, NULL);
8635     ReleaseDC(infoPtr->hwndSelf, hdc_wnd);
8636 
8637     SetRect(&rc, 0, 0, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON));
8638     hbm_orig = SelectObject(hdc, hbm_mask);
8639     FillRect(hdc, &rc, hbr_white);
8640     InflateRect(&rc, -2, -2);
8641     FillRect(hdc, &rc, hbr_black);
8642 
8643     SelectObject(hdc, hbm_im);
8644     DrawFrameControl(hdc, &rc, DFC_BUTTON, DFCS_BUTTONCHECK | DFCS_MONO);
8645     SelectObject(hdc, hbm_orig);
8646     ImageList_Add(himl, hbm_im, hbm_mask);
8647 
8648     SelectObject(hdc, hbm_im);
8649     DrawFrameControl(hdc, &rc, DFC_BUTTON, DFCS_BUTTONCHECK | DFCS_MONO | DFCS_CHECKED);
8650     SelectObject(hdc, hbm_orig);
8651     ImageList_Add(himl, hbm_im, hbm_mask);
8652 
8653     DeleteObject(hbm_mask);
8654     DeleteObject(hbm_im);
8655     DeleteDC(hdc);
8656 
8657     return himl;
8658 }
8659 
8660 /***
8661  * DESCRIPTION:
8662  * Sets the extended listview style.
8663  *
8664  * PARAMETERS:
8665  * [I] infoPtr : valid pointer to the listview structure
8666  * [I] dwMask : mask
8667  * [I] dwStyle : style
8668  *
8669  * RETURN:
8670  *   SUCCESS : previous style
8671  *   FAILURE : 0
8672  */
8673 static DWORD LISTVIEW_SetExtendedListViewStyle(LISTVIEW_INFO *infoPtr, DWORD mask, DWORD ex_style)
8674 {
8675     DWORD old_ex_style = infoPtr->dwLvExStyle;
8676 
8677     TRACE("mask=0x%08x, ex_style=0x%08x\n", mask, ex_style);
8678 
8679     /* set new style */
8680     if (mask)
8681 	infoPtr->dwLvExStyle = (old_ex_style & ~mask) | (ex_style & mask);
8682     else
8683 	infoPtr->dwLvExStyle = ex_style;
8684 
8685     if((infoPtr->dwLvExStyle ^ old_ex_style) & LVS_EX_CHECKBOXES)
8686     {
8687         HIMAGELIST himl = 0;
8688         if(infoPtr->dwLvExStyle & LVS_EX_CHECKBOXES)
8689         {
8690             LVITEMW item;
8691             item.mask = LVIF_STATE;
8692             item.stateMask = LVIS_STATEIMAGEMASK;
8693             item.state = INDEXTOSTATEIMAGEMASK(1);
8694             LISTVIEW_SetItemState(infoPtr, -1, &item);
8695 
8696             himl = LISTVIEW_CreateCheckBoxIL(infoPtr);
8697             if(!(infoPtr->dwStyle & LVS_SHAREIMAGELISTS))
8698                 ImageList_Destroy(infoPtr->himlState);
8699         }
8700         himl = LISTVIEW_SetImageList(infoPtr, LVSIL_STATE, himl);
8701         /*   checkbox list replaces previous custom list or... */
8702         if(((infoPtr->dwLvExStyle & LVS_EX_CHECKBOXES) &&
8703            !(infoPtr->dwStyle & LVS_SHAREIMAGELISTS)) ||
8704             /* ...previous was checkbox list */
8705             (old_ex_style & LVS_EX_CHECKBOXES))
8706             ImageList_Destroy(himl);
8707     }
8708 
8709     if((infoPtr->dwLvExStyle ^ old_ex_style) & LVS_EX_HEADERDRAGDROP)
8710     {
8711         DWORD style;
8712 
8713         /* if not already created */
8714         LISTVIEW_CreateHeader(infoPtr);
8715 
8716         style = GetWindowLongW(infoPtr->hwndHeader, GWL_STYLE);
8717         if (infoPtr->dwLvExStyle & LVS_EX_HEADERDRAGDROP)
8718             style |= HDS_DRAGDROP;
8719         else
8720             style &= ~HDS_DRAGDROP;
8721         SetWindowLongW(infoPtr->hwndHeader, GWL_STYLE, style);
8722     }
8723 
8724     /* GRIDLINES adds decoration at top so changes sizes */
8725     if((infoPtr->dwLvExStyle ^ old_ex_style) & LVS_EX_GRIDLINES)
8726     {
8727         LISTVIEW_CreateHeader(infoPtr);
8728         LISTVIEW_UpdateSize(infoPtr);
8729     }
8730 
8731     if((infoPtr->dwLvExStyle ^ old_ex_style) & LVS_EX_FULLROWSELECT)
8732     {
8733         LISTVIEW_CreateHeader(infoPtr);
8734     }
8735 
8736     if((infoPtr->dwLvExStyle ^ old_ex_style) & LVS_EX_TRANSPARENTBKGND)
8737     {
8738         if (infoPtr->dwLvExStyle & LVS_EX_TRANSPARENTBKGND)
8739             LISTVIEW_SetBkColor(infoPtr, CLR_NONE);
8740     }
8741 
8742     if((infoPtr->dwLvExStyle ^ old_ex_style) & LVS_EX_HEADERINALLVIEWS)
8743     {
8744         if (infoPtr->dwLvExStyle & LVS_EX_HEADERINALLVIEWS)
8745             LISTVIEW_CreateHeader(infoPtr);
8746         else
8747             ShowWindow(infoPtr->hwndHeader, SW_HIDE);
8748         LISTVIEW_UpdateSize(infoPtr);
8749         LISTVIEW_UpdateScroll(infoPtr);
8750     }
8751 
8752 #ifdef __REACTOS__
8753     if ((infoPtr->dwLvExStyle & LVS_EX_SNAPTOGRID) > (old_ex_style & LVS_EX_SNAPTOGRID))
8754     {
8755         LISTVIEW_Arrange(infoPtr, LVA_SNAPTOGRID);
8756     }
8757 #endif
8758 
8759     LISTVIEW_InvalidateList(infoPtr);
8760     return old_ex_style;
8761 }
8762 
8763 /***
8764  * DESCRIPTION:
8765  * Sets the new hot cursor used during hot tracking and hover selection.
8766  *
8767  * PARAMETER(S):
8768  * [I] infoPtr : valid pointer to the listview structure
8769  * [I] hCursor : the new hot cursor handle
8770  *
8771  * RETURN:
8772  * Returns the previous hot cursor
8773  */
8774 static HCURSOR LISTVIEW_SetHotCursor(LISTVIEW_INFO *infoPtr, HCURSOR hCursor)
8775 {
8776     HCURSOR oldCursor = infoPtr->hHotCursor;
8777 
8778     infoPtr->hHotCursor = hCursor;
8779 
8780     return oldCursor;
8781 }
8782 
8783 
8784 /***
8785  * DESCRIPTION:
8786  * Sets the hot item index.
8787  *
8788  * PARAMETERS:
8789  * [I] infoPtr : valid pointer to the listview structure
8790  * [I] iIndex : index
8791  *
8792  * RETURN:
8793  *   SUCCESS : previous hot item index
8794  *   FAILURE : -1 (no hot item)
8795  */
8796 static INT LISTVIEW_SetHotItem(LISTVIEW_INFO *infoPtr, INT iIndex)
8797 {
8798     INT iOldIndex = infoPtr->nHotItem;
8799 
8800     infoPtr->nHotItem = iIndex;
8801 
8802     return iOldIndex;
8803 }
8804 
8805 
8806 /***
8807  * DESCRIPTION:
8808  * Sets the amount of time the cursor must hover over an item before it is selected.
8809  *
8810  * PARAMETER(S):
8811  * [I] infoPtr : valid pointer to the listview structure
8812  * [I] dwHoverTime : hover time, if -1 the hover time is set to the default
8813  *
8814  * RETURN:
8815  * Returns the previous hover time
8816  */
8817 static DWORD LISTVIEW_SetHoverTime(LISTVIEW_INFO *infoPtr, DWORD dwHoverTime)
8818 {
8819     DWORD oldHoverTime = infoPtr->dwHoverTime;
8820 
8821     infoPtr->dwHoverTime = dwHoverTime;
8822 
8823     return oldHoverTime;
8824 }
8825 
8826 /***
8827  * DESCRIPTION:
8828  * Sets spacing for icons of LVS_ICON style.
8829  *
8830  * PARAMETER(S):
8831  * [I] infoPtr : valid pointer to the listview structure
8832  * [I] cx : horizontal spacing (-1 = system spacing, 0 = autosize)
8833  * [I] cy : vertical spacing (-1 = system spacing, 0 = autosize)
8834  *
8835  * RETURN:
8836  *   MAKELONG(oldcx, oldcy)
8837  */
8838 static DWORD LISTVIEW_SetIconSpacing(LISTVIEW_INFO *infoPtr, INT cx, INT cy)
8839 {
8840     INT iconWidth = 0, iconHeight = 0;
8841     DWORD oldspacing = MAKELONG(infoPtr->iconSpacing.cx, infoPtr->iconSpacing.cy);
8842 
8843     TRACE("requested=(%d,%d)\n", cx, cy);
8844 
8845     /* set to defaults, if instructed to */
8846     if (cx == -1 && cy == -1)
8847     {
8848         infoPtr->autoSpacing = TRUE;
8849         if (infoPtr->himlNormal)
8850             ImageList_GetIconSize(infoPtr->himlNormal, &iconWidth, &iconHeight);
8851         cx = GetSystemMetrics(SM_CXICONSPACING) - GetSystemMetrics(SM_CXICON) + iconWidth;
8852         cy = GetSystemMetrics(SM_CYICONSPACING) - GetSystemMetrics(SM_CYICON) + iconHeight;
8853     }
8854     else
8855         infoPtr->autoSpacing = FALSE;
8856 
8857     /* if 0 then keep width */
8858     if (cx != 0)
8859         infoPtr->iconSpacing.cx = cx;
8860 
8861     /* if 0 then keep height */
8862     if (cy != 0)
8863         infoPtr->iconSpacing.cy = cy;
8864 
8865     TRACE("old=(%d,%d), new=(%d,%d), iconSize=(%d,%d), ntmH=%d\n",
8866           LOWORD(oldspacing), HIWORD(oldspacing), infoPtr->iconSpacing.cx, infoPtr->iconSpacing.cy,
8867 	  infoPtr->iconSize.cx, infoPtr->iconSize.cy,
8868 	  infoPtr->ntmHeight);
8869 
8870     /* these depend on the iconSpacing */
8871     LISTVIEW_UpdateItemSize(infoPtr);
8872 
8873     return oldspacing;
8874 }
8875 
8876 static inline void set_icon_size(SIZE *size, HIMAGELIST himl, BOOL is_small)
8877 {
8878     INT cx, cy;
8879 
8880     if (himl && ImageList_GetIconSize(himl, &cx, &cy))
8881     {
8882 	size->cx = cx;
8883 	size->cy = cy;
8884     }
8885     else
8886     {
8887 	size->cx = GetSystemMetrics(is_small ? SM_CXSMICON : SM_CXICON);
8888 	size->cy = GetSystemMetrics(is_small ? SM_CYSMICON : SM_CYICON);
8889     }
8890 }
8891 
8892 /***
8893  * DESCRIPTION:
8894  * Sets image lists.
8895  *
8896  * PARAMETER(S):
8897  * [I] infoPtr : valid pointer to the listview structure
8898  * [I] nType : image list type
8899  * [I] himl : image list handle
8900  *
8901  * RETURN:
8902  *   SUCCESS : old image list
8903  *   FAILURE : NULL
8904  */
8905 static HIMAGELIST LISTVIEW_SetImageList(LISTVIEW_INFO *infoPtr, INT nType, HIMAGELIST himl)
8906 {
8907     INT oldHeight = infoPtr->nItemHeight;
8908     HIMAGELIST himlOld = 0;
8909 
8910     TRACE("(nType=%d, himl=%p)\n", nType, himl);
8911 
8912     switch (nType)
8913     {
8914     case LVSIL_NORMAL:
8915         himlOld = infoPtr->himlNormal;
8916         infoPtr->himlNormal = himl;
8917         if (infoPtr->uView == LV_VIEW_ICON) set_icon_size(&infoPtr->iconSize, himl, FALSE);
8918         if (infoPtr->autoSpacing)
8919             LISTVIEW_SetIconSpacing(infoPtr, -1, -1);
8920     break;
8921 
8922     case LVSIL_SMALL:
8923         himlOld = infoPtr->himlSmall;
8924         infoPtr->himlSmall = himl;
8925         if (infoPtr->uView != LV_VIEW_ICON) set_icon_size(&infoPtr->iconSize, himl, TRUE);
8926         if (infoPtr->hwndHeader)
8927             SendMessageW(infoPtr->hwndHeader, HDM_SETIMAGELIST, 0, (LPARAM)himl);
8928     break;
8929 
8930     case LVSIL_STATE:
8931         himlOld = infoPtr->himlState;
8932         infoPtr->himlState = himl;
8933         set_icon_size(&infoPtr->iconStateSize, himl, TRUE);
8934         ImageList_SetBkColor(infoPtr->himlState, CLR_NONE);
8935     break;
8936 
8937     default:
8938         ERR("Unknown icon type=%d\n", nType);
8939 	return NULL;
8940     }
8941 
8942     infoPtr->nItemHeight = LISTVIEW_CalculateItemHeight(infoPtr);
8943     if (infoPtr->nItemHeight != oldHeight)
8944         LISTVIEW_UpdateScroll(infoPtr);
8945 
8946     return himlOld;
8947 }
8948 
8949 /***
8950  * DESCRIPTION:
8951  * Preallocates memory (does *not* set the actual count of items !)
8952  *
8953  * PARAMETER(S):
8954  * [I] infoPtr : valid pointer to the listview structure
8955  * [I] nItems : item count (projected number of items to allocate)
8956  * [I] dwFlags : update flags
8957  *
8958  * RETURN:
8959  *   SUCCESS : TRUE
8960  *   FAILURE : FALSE
8961  */
8962 static BOOL LISTVIEW_SetItemCount(LISTVIEW_INFO *infoPtr, INT nItems, DWORD dwFlags)
8963 {
8964     TRACE("(nItems=%d, dwFlags=%x)\n", nItems, dwFlags);
8965 
8966     if (infoPtr->dwStyle & LVS_OWNERDATA)
8967     {
8968 	INT nOldCount = infoPtr->nItemCount;
8969 	infoPtr->nItemCount = nItems;
8970 
8971 	if (nItems < nOldCount)
8972 	{
8973 	    RANGE range = { nItems, nOldCount };
8974 	    ranges_del(infoPtr->selectionRanges, range);
8975 	    if (infoPtr->nFocusedItem >= nItems)
8976 	    {
8977 		LISTVIEW_SetItemFocus(infoPtr, -1);
8978                 infoPtr->nFocusedItem = -1;
8979 		SetRectEmpty(&infoPtr->rcFocus);
8980 	    }
8981 	}
8982 
8983 	LISTVIEW_UpdateScroll(infoPtr);
8984 
8985 	/* the flags are valid only in ownerdata report and list modes */
8986 	if (infoPtr->uView == LV_VIEW_ICON || infoPtr->uView == LV_VIEW_SMALLICON) dwFlags = 0;
8987 
8988 	if (!(dwFlags & LVSICF_NOSCROLL) && infoPtr->nFocusedItem != -1)
8989 	    LISTVIEW_EnsureVisible(infoPtr, infoPtr->nFocusedItem, FALSE);
8990 
8991 	if (!(dwFlags & LVSICF_NOINVALIDATEALL))
8992 	    LISTVIEW_InvalidateList(infoPtr);
8993 	else
8994 	{
8995 	    INT nFrom, nTo;
8996 	    POINT Origin;
8997 	    RECT rcErase;
8998 
8999 	    LISTVIEW_GetOrigin(infoPtr, &Origin);
9000     	    nFrom = min(nOldCount, nItems);
9001 	    nTo = max(nOldCount, nItems);
9002 
9003 	    if (infoPtr->uView == LV_VIEW_DETAILS)
9004 	    {
9005                 SetRect(&rcErase, 0, nFrom * infoPtr->nItemHeight, infoPtr->nItemWidth,
9006                         nTo * infoPtr->nItemHeight);
9007 		OffsetRect(&rcErase, Origin.x, Origin.y);
9008 		if (IntersectRect(&rcErase, &rcErase, &infoPtr->rcList))
9009 		    LISTVIEW_InvalidateRect(infoPtr, &rcErase);
9010 	    }
9011 	    else /* LV_VIEW_LIST */
9012 	    {
9013 		INT nPerCol = LISTVIEW_GetCountPerColumn(infoPtr);
9014 
9015 		rcErase.left = (nFrom / nPerCol) * infoPtr->nItemWidth;
9016 		rcErase.top = (nFrom % nPerCol) * infoPtr->nItemHeight;
9017 		rcErase.right = rcErase.left + infoPtr->nItemWidth;
9018 		rcErase.bottom = nPerCol * infoPtr->nItemHeight;
9019 		OffsetRect(&rcErase, Origin.x, Origin.y);
9020 		if (IntersectRect(&rcErase, &rcErase, &infoPtr->rcList))
9021 		    LISTVIEW_InvalidateRect(infoPtr, &rcErase);
9022 
9023 		rcErase.left = (nFrom / nPerCol + 1) * infoPtr->nItemWidth;
9024 		rcErase.top = 0;
9025 		rcErase.right = (nTo / nPerCol + 1) * infoPtr->nItemWidth;
9026 		rcErase.bottom = nPerCol * infoPtr->nItemHeight;
9027 		OffsetRect(&rcErase, Origin.x, Origin.y);
9028 		if (IntersectRect(&rcErase, &rcErase, &infoPtr->rcList))
9029 		    LISTVIEW_InvalidateRect(infoPtr, &rcErase);
9030 	    }
9031 	}
9032     }
9033     else
9034     {
9035 	/* According to MSDN for non-LVS_OWNERDATA this is just
9036 	 * a performance issue. The control allocates its internal
9037 	 * data structures for the number of items specified. It
9038 	 * cuts down on the number of memory allocations. Therefore
9039 	 * we will just issue a WARN here
9040 	 */
9041 	WARN("for non-ownerdata performance option not implemented.\n");
9042     }
9043 
9044     return TRUE;
9045 }
9046 
9047 /***
9048  * DESCRIPTION:
9049  * Sets the position of an item.
9050  *
9051  * PARAMETER(S):
9052  * [I] infoPtr : valid pointer to the listview structure
9053  * [I] nItem : item index
9054  * [I] pt : coordinate
9055  *
9056  * RETURN:
9057  *   SUCCESS : TRUE
9058  *   FAILURE : FALSE
9059  */
9060 static BOOL LISTVIEW_SetItemPosition(LISTVIEW_INFO *infoPtr, INT nItem, const POINT *pt)
9061 {
9062     POINT Origin, Pt;
9063 
9064     TRACE("(nItem=%d, pt=%s)\n", nItem, wine_dbgstr_point(pt));
9065 
9066     if (!pt || nItem < 0 || nItem >= infoPtr->nItemCount ||
9067 	!(infoPtr->uView == LV_VIEW_ICON || infoPtr->uView == LV_VIEW_SMALLICON)) return FALSE;
9068 
9069 #ifdef __REACTOS__
9070     /* FIXME:  This should really call snap to grid if auto-arrange is enabled
9071        and limit the size of the grid to nItemCount elements */
9072     if (is_autoarrange(infoPtr)) return FALSE;
9073 #endif
9074 
9075     Pt = *pt;
9076     LISTVIEW_GetOrigin(infoPtr, &Origin);
9077 
9078     /* This point value seems to be an undocumented feature.
9079      * The best guess is that it means either at the origin,
9080      * or at true beginning of the list. I will assume the origin. */
9081     if ((Pt.x == -1) && (Pt.y == -1))
9082 	Pt = Origin;
9083 
9084     if (infoPtr->uView == LV_VIEW_ICON)
9085     {
9086 	Pt.x -= (infoPtr->nItemWidth - infoPtr->iconSize.cx) / 2;
9087 	Pt.y -= ICON_TOP_PADDING;
9088     }
9089     Pt.x -= Origin.x;
9090     Pt.y -= Origin.y;
9091 
9092 #ifdef __REACTOS__
9093     if (infoPtr->dwLvExStyle & LVS_EX_SNAPTOGRID)
9094     {
9095         Pt.x = max(0, Pt.x + (infoPtr->nItemWidth >> 1) - (Pt.x + (infoPtr->nItemWidth >> 1)) % infoPtr->nItemWidth);
9096         Pt.y = max(0, Pt.y + (infoPtr->nItemHeight >> 1) - (Pt.y + (infoPtr->nItemHeight >> 1)) % infoPtr->nItemHeight);
9097     }
9098 #endif
9099 
9100     return LISTVIEW_MoveIconTo(infoPtr, nItem, &Pt, FALSE);
9101 }
9102 
9103 /***
9104  * DESCRIPTION:
9105  * Sets the state of one or many items.
9106  *
9107  * PARAMETER(S):
9108  * [I] infoPtr : valid pointer to the listview structure
9109  * [I] nItem : item index
9110  * [I] item  : item or subitem info
9111  *
9112  * RETURN:
9113  *   SUCCESS : TRUE
9114  *   FAILURE : FALSE
9115  */
9116 static BOOL LISTVIEW_SetItemState(LISTVIEW_INFO *infoPtr, INT nItem, const LVITEMW *item)
9117 {
9118     BOOL ret = TRUE;
9119     LVITEMW lvItem;
9120 
9121     if (!item) return FALSE;
9122 
9123     lvItem.iItem = nItem;
9124     lvItem.iSubItem = 0;
9125     lvItem.mask = LVIF_STATE;
9126     lvItem.state = item->state;
9127     lvItem.stateMask = item->stateMask;
9128     TRACE("item=%s\n", debuglvitem_t(&lvItem, TRUE));
9129 
9130     if (nItem == -1)
9131     {
9132         UINT oldstate = 0;
9133         DWORD old_mask;
9134 
9135         /* special case optimization for recurring attempt to deselect all */
9136         if (lvItem.state == 0 && lvItem.stateMask == LVIS_SELECTED && !LISTVIEW_GetSelectedCount(infoPtr))
9137             return TRUE;
9138 
9139 	/* select all isn't allowed in LVS_SINGLESEL */
9140 	if ((lvItem.state & lvItem.stateMask & LVIS_SELECTED) && (infoPtr->dwStyle & LVS_SINGLESEL))
9141 	    return FALSE;
9142 
9143 	/* focus all isn't allowed */
9144 	if (lvItem.state & lvItem.stateMask & LVIS_FOCUSED) return FALSE;
9145 
9146         old_mask = infoPtr->notify_mask & NOTIFY_MASK_ITEM_CHANGE;
9147         if (infoPtr->dwStyle & LVS_OWNERDATA)
9148         {
9149             infoPtr->notify_mask &= ~NOTIFY_MASK_ITEM_CHANGE;
9150             if (!(lvItem.state & LVIS_SELECTED) && LISTVIEW_GetSelectedCount(infoPtr))
9151                 oldstate |= LVIS_SELECTED;
9152             if (infoPtr->nFocusedItem != -1) oldstate |= LVIS_FOCUSED;
9153         }
9154 
9155     	/* apply to all items */
9156     	for (lvItem.iItem = 0; lvItem.iItem < infoPtr->nItemCount; lvItem.iItem++)
9157 	    if (!LISTVIEW_SetItemT(infoPtr, &lvItem, TRUE)) ret = FALSE;
9158 
9159         if (infoPtr->dwStyle & LVS_OWNERDATA)
9160         {
9161             NMLISTVIEW nmlv;
9162 
9163             infoPtr->notify_mask |= old_mask;
9164 
9165             nmlv.iItem = -1;
9166             nmlv.iSubItem = 0;
9167             nmlv.uNewState = lvItem.state & lvItem.stateMask;
9168             nmlv.uOldState = oldstate & lvItem.stateMask;
9169             nmlv.uChanged = LVIF_STATE;
9170             nmlv.ptAction.x = nmlv.ptAction.y = 0;
9171             nmlv.lParam = 0;
9172 
9173             notify_listview(infoPtr, LVN_ITEMCHANGED, &nmlv);
9174         }
9175     }
9176     else
9177 	ret = LISTVIEW_SetItemT(infoPtr, &lvItem, TRUE);
9178 
9179     return ret;
9180 }
9181 
9182 /***
9183  * DESCRIPTION:
9184  * Sets the text of an item or subitem.
9185  *
9186  * PARAMETER(S):
9187  * [I] hwnd : window handle
9188  * [I] nItem : item index
9189  * [I] lpLVItem : item or subitem info
9190  * [I] isW : TRUE if input is Unicode
9191  *
9192  * RETURN:
9193  *   SUCCESS : TRUE
9194  *   FAILURE : FALSE
9195  */
9196 static BOOL LISTVIEW_SetItemTextT(LISTVIEW_INFO *infoPtr, INT nItem, const LVITEMW *lpLVItem, BOOL isW)
9197 {
9198     LVITEMW lvItem;
9199 
9200     if (!lpLVItem || nItem < 0 || nItem >= infoPtr->nItemCount) return FALSE;
9201     if (infoPtr->dwStyle & LVS_OWNERDATA) return FALSE;
9202 
9203     lvItem.iItem = nItem;
9204     lvItem.iSubItem = lpLVItem->iSubItem;
9205     lvItem.mask = LVIF_TEXT;
9206     lvItem.pszText = lpLVItem->pszText;
9207     lvItem.cchTextMax = lpLVItem->cchTextMax;
9208 
9209     TRACE("(nItem=%d, lpLVItem=%s, isW=%d)\n", nItem, debuglvitem_t(&lvItem, isW), isW);
9210 
9211     return LISTVIEW_SetItemT(infoPtr, &lvItem, isW);
9212 }
9213 
9214 /***
9215  * DESCRIPTION:
9216  * Set item index that marks the start of a multiple selection.
9217  *
9218  * PARAMETER(S):
9219  * [I] infoPtr : valid pointer to the listview structure
9220  * [I] nIndex : index
9221  *
9222  * RETURN:
9223  * Index number or -1 if there is no selection mark.
9224  */
9225 static INT LISTVIEW_SetSelectionMark(LISTVIEW_INFO *infoPtr, INT nIndex)
9226 {
9227   INT nOldIndex = infoPtr->nSelectionMark;
9228 
9229   TRACE("(nIndex=%d)\n", nIndex);
9230 
9231   if (nIndex >= -1 && nIndex < infoPtr->nItemCount)
9232     infoPtr->nSelectionMark = nIndex;
9233 
9234   return nOldIndex;
9235 }
9236 
9237 /***
9238  * DESCRIPTION:
9239  * Sets the text background color.
9240  *
9241  * PARAMETER(S):
9242  * [I] infoPtr : valid pointer to the listview structure
9243  * [I] color   : text background color
9244  *
9245  * RETURN:
9246  *   SUCCESS : TRUE
9247  *   FAILURE : FALSE
9248  */
9249 static BOOL LISTVIEW_SetTextBkColor(LISTVIEW_INFO *infoPtr, COLORREF color)
9250 {
9251     TRACE("(color=%x)\n", color);
9252 
9253     infoPtr->clrTextBk = color;
9254     return TRUE;
9255 }
9256 
9257 /***
9258  * DESCRIPTION:
9259  * Sets the text foreground color.
9260  *
9261  * PARAMETER(S):
9262  * [I] infoPtr : valid pointer to the listview structure
9263  * [I] color   : text color
9264  *
9265  * RETURN:
9266  *   SUCCESS : TRUE
9267  *   FAILURE : FALSE
9268  */
9269 static BOOL LISTVIEW_SetTextColor (LISTVIEW_INFO *infoPtr, COLORREF color)
9270 {
9271     TRACE("(color=%x)\n", color);
9272 
9273     infoPtr->clrText = color;
9274     return TRUE;
9275 }
9276 
9277 /***
9278  * DESCRIPTION:
9279  * Sets new ToolTip window to ListView control.
9280  *
9281  * PARAMETER(S):
9282  * [I] infoPtr        : valid pointer to the listview structure
9283  * [I] hwndNewToolTip : handle to new ToolTip
9284  *
9285  * RETURN:
9286  *   old tool tip
9287  */
9288 static HWND LISTVIEW_SetToolTips( LISTVIEW_INFO *infoPtr, HWND hwndNewToolTip)
9289 {
9290   HWND hwndOldToolTip = infoPtr->hwndToolTip;
9291   infoPtr->hwndToolTip = hwndNewToolTip;
9292   return hwndOldToolTip;
9293 }
9294 
9295 /*
9296  * DESCRIPTION:
9297  *   sets the Unicode character format flag for the control
9298  * PARAMETER(S):
9299  *    [I] infoPtr         :valid pointer to the listview structure
9300  *    [I] fUnicode        :true to switch to UNICODE false to switch to ANSI
9301  *
9302  * RETURN:
9303  *    Old Unicode Format
9304  */
9305 static BOOL LISTVIEW_SetUnicodeFormat( LISTVIEW_INFO *infoPtr, BOOL unicode)
9306 {
9307   SHORT rc = infoPtr->notifyFormat;
9308   infoPtr->notifyFormat = (unicode) ? NFR_UNICODE : NFR_ANSI;
9309   return rc == NFR_UNICODE;
9310 }
9311 
9312 /*
9313  * DESCRIPTION:
9314  *   sets the control view mode
9315  * PARAMETER(S):
9316  *    [I] infoPtr         :valid pointer to the listview structure
9317  *    [I] nView           :new view mode value
9318  *
9319  * RETURN:
9320  *    SUCCESS:  1
9321  *    FAILURE: -1
9322  */
9323 static INT LISTVIEW_SetView(LISTVIEW_INFO *infoPtr, DWORD nView)
9324 {
9325   HIMAGELIST himl;
9326 
9327   if (infoPtr->uView == nView) return 1;
9328 
9329   if ((INT)nView < 0 || nView > LV_VIEW_MAX) return -1;
9330   if (nView == LV_VIEW_TILE)
9331   {
9332       FIXME("View LV_VIEW_TILE unimplemented\n");
9333       return -1;
9334   }
9335 
9336   infoPtr->uView = nView;
9337 
9338   SendMessageW(infoPtr->hwndEdit, WM_KILLFOCUS, 0, 0);
9339   ShowWindow(infoPtr->hwndHeader, SW_HIDE);
9340 
9341   ShowScrollBar(infoPtr->hwndSelf, SB_BOTH, FALSE);
9342   SetRectEmpty(&infoPtr->rcFocus);
9343 
9344   himl = (nView == LV_VIEW_ICON ? infoPtr->himlNormal : infoPtr->himlSmall);
9345   set_icon_size(&infoPtr->iconSize, himl, nView != LV_VIEW_ICON);
9346 
9347   switch (nView)
9348   {
9349   case LV_VIEW_ICON:
9350   case LV_VIEW_SMALLICON:
9351       LISTVIEW_Arrange(infoPtr, LVA_DEFAULT);
9352       break;
9353   case LV_VIEW_DETAILS:
9354   {
9355       HDLAYOUT hl;
9356       WINDOWPOS wp;
9357 
9358       LISTVIEW_CreateHeader( infoPtr );
9359 
9360       hl.prc = &infoPtr->rcList;
9361       hl.pwpos = &wp;
9362       SendMessageW(infoPtr->hwndHeader, HDM_LAYOUT, 0, (LPARAM)&hl);
9363       SetWindowPos(infoPtr->hwndHeader, infoPtr->hwndSelf, wp.x, wp.y, wp.cx, wp.cy,
9364                    wp.flags | ((infoPtr->dwStyle & LVS_NOCOLUMNHEADER) ? SWP_HIDEWINDOW : SWP_SHOWWINDOW));
9365       break;
9366   }
9367   case LV_VIEW_LIST:
9368       break;
9369   }
9370 
9371   LISTVIEW_UpdateItemSize(infoPtr);
9372   LISTVIEW_UpdateSize(infoPtr);
9373   LISTVIEW_UpdateScroll(infoPtr);
9374   LISTVIEW_InvalidateList(infoPtr);
9375 
9376   TRACE("nView=%d\n", nView);
9377 
9378   return 1;
9379 }
9380 
9381 /* LISTVIEW_SetWorkAreas */
9382 
9383 /***
9384  * DESCRIPTION:
9385  * Callback internally used by LISTVIEW_SortItems() in response of LVM_SORTITEMS
9386  *
9387  * PARAMETER(S):
9388  * [I] first : pointer to first ITEM_INFO to compare
9389  * [I] second : pointer to second ITEM_INFO to compare
9390  * [I] lParam : HWND of control
9391  *
9392  * RETURN:
9393  *   if first comes before second : negative
9394  *   if first comes after second : positive
9395  *   if first and second are equivalent : zero
9396  */
9397 static INT WINAPI LISTVIEW_CallBackCompare(LPVOID first, LPVOID second, LPARAM lParam)
9398 {
9399   LISTVIEW_INFO *infoPtr = (LISTVIEW_INFO *)lParam;
9400   ITEM_INFO* lv_first = DPA_GetPtr( first, 0 );
9401   ITEM_INFO* lv_second = DPA_GetPtr( second, 0 );
9402 
9403   /* Forward the call to the client defined callback */
9404   return (infoPtr->pfnCompare)( lv_first->lParam , lv_second->lParam, infoPtr->lParamSort );
9405 }
9406 
9407 /***
9408  * DESCRIPTION:
9409  * Callback internally used by LISTVIEW_SortItems() in response of LVM_SORTITEMSEX
9410  *
9411  * PARAMETER(S):
9412  * [I] first : pointer to first ITEM_INFO to compare
9413  * [I] second : pointer to second ITEM_INFO to compare
9414  * [I] lParam : HWND of control
9415  *
9416  * RETURN:
9417  *   if first comes before second : negative
9418  *   if first comes after second : positive
9419  *   if first and second are equivalent : zero
9420  */
9421 static INT WINAPI LISTVIEW_CallBackCompareEx(LPVOID first, LPVOID second, LPARAM lParam)
9422 {
9423   LISTVIEW_INFO *infoPtr = (LISTVIEW_INFO *)lParam;
9424   INT first_idx  = DPA_GetPtrIndex( infoPtr->hdpaItems, first  );
9425   INT second_idx = DPA_GetPtrIndex( infoPtr->hdpaItems, second );
9426 
9427   /* Forward the call to the client defined callback */
9428   return (infoPtr->pfnCompare)( first_idx, second_idx, infoPtr->lParamSort );
9429 }
9430 
9431 /***
9432  * DESCRIPTION:
9433  * Sorts the listview items.
9434  *
9435  * PARAMETER(S):
9436  * [I] infoPtr : valid pointer to the listview structure
9437  * [I] pfnCompare : application-defined value
9438  * [I] lParamSort : pointer to comparison callback
9439  * [I] IsEx : TRUE when LVM_SORTITEMSEX used
9440  *
9441  * RETURN:
9442  *   SUCCESS : TRUE
9443  *   FAILURE : FALSE
9444  */
9445 static BOOL LISTVIEW_SortItems(LISTVIEW_INFO *infoPtr, PFNLVCOMPARE pfnCompare,
9446                                LPARAM lParamSort, BOOL IsEx)
9447 {
9448     HDPA hdpaSubItems;
9449     ITEM_INFO *lpItem;
9450     LPVOID selectionMarkItem = NULL;
9451     LPVOID focusedItem = NULL;
9452     int i;
9453 
9454     TRACE("(pfnCompare=%p, lParamSort=%lx)\n", pfnCompare, lParamSort);
9455 
9456     if (infoPtr->dwStyle & LVS_OWNERDATA) return FALSE;
9457 
9458     if (!pfnCompare) return FALSE;
9459     if (!infoPtr->hdpaItems) return FALSE;
9460 
9461     /* if there are 0 or 1 items, there is no need to sort */
9462     if (infoPtr->nItemCount < 2) return TRUE;
9463 
9464     /* clear selection */
9465     ranges_clear(infoPtr->selectionRanges);
9466 
9467     /* save selection mark and focused item */
9468     if (infoPtr->nSelectionMark >= 0)
9469         selectionMarkItem = DPA_GetPtr(infoPtr->hdpaItems, infoPtr->nSelectionMark);
9470     if (infoPtr->nFocusedItem >= 0)
9471         focusedItem = DPA_GetPtr(infoPtr->hdpaItems, infoPtr->nFocusedItem);
9472 
9473     infoPtr->pfnCompare = pfnCompare;
9474     infoPtr->lParamSort = lParamSort;
9475     if (IsEx)
9476         DPA_Sort(infoPtr->hdpaItems, LISTVIEW_CallBackCompareEx, (LPARAM)infoPtr);
9477     else
9478         DPA_Sort(infoPtr->hdpaItems, LISTVIEW_CallBackCompare, (LPARAM)infoPtr);
9479 
9480     /* restore selection ranges */
9481     for (i=0; i < infoPtr->nItemCount; i++)
9482     {
9483         hdpaSubItems = DPA_GetPtr(infoPtr->hdpaItems, i);
9484         lpItem = DPA_GetPtr(hdpaSubItems, 0);
9485 
9486 	if (lpItem->state & LVIS_SELECTED)
9487 	    ranges_additem(infoPtr->selectionRanges, i);
9488     }
9489     /* restore selection mark and focused item */
9490     infoPtr->nSelectionMark = DPA_GetPtrIndex(infoPtr->hdpaItems, selectionMarkItem);
9491     infoPtr->nFocusedItem   = DPA_GetPtrIndex(infoPtr->hdpaItems, focusedItem);
9492 
9493     /* I believe nHotItem should be left alone, see LISTVIEW_ShiftIndices */
9494 
9495     /* refresh the display */
9496     LISTVIEW_InvalidateList(infoPtr);
9497     return TRUE;
9498 }
9499 
9500 /***
9501  * DESCRIPTION:
9502  * Update theme handle after a theme change.
9503  *
9504  * PARAMETER(S):
9505  * [I] infoPtr : valid pointer to the listview structure
9506  *
9507  * RETURN:
9508  *   SUCCESS : 0
9509  *   FAILURE : something else
9510  */
9511 static LRESULT LISTVIEW_ThemeChanged(const LISTVIEW_INFO *infoPtr)
9512 {
9513     HTHEME theme = GetWindowTheme(infoPtr->hwndSelf);
9514     CloseThemeData(theme);
9515     OpenThemeData(infoPtr->hwndSelf, themeClass);
9516     return 0;
9517 }
9518 
9519 /***
9520  * DESCRIPTION:
9521  * Updates an items or rearranges the listview control.
9522  *
9523  * PARAMETER(S):
9524  * [I] infoPtr : valid pointer to the listview structure
9525  * [I] nItem : item index
9526  *
9527  * RETURN:
9528  *   SUCCESS : TRUE
9529  *   FAILURE : FALSE
9530  */
9531 static BOOL LISTVIEW_Update(LISTVIEW_INFO *infoPtr, INT nItem)
9532 {
9533     TRACE("(nItem=%d)\n", nItem);
9534 
9535     if (nItem < 0 || nItem >= infoPtr->nItemCount) return FALSE;
9536 
9537     /* rearrange with default alignment style */
9538     if (is_autoarrange(infoPtr))
9539 	LISTVIEW_Arrange(infoPtr, LVA_DEFAULT);
9540     else
9541 	LISTVIEW_InvalidateItem(infoPtr, nItem);
9542 
9543     return TRUE;
9544 }
9545 
9546 /***
9547  * DESCRIPTION:
9548  * Draw the track line at the place defined in the infoPtr structure.
9549  * The line is drawn with a XOR pen so drawing the line for the second time
9550  * in the same place erases the line.
9551  *
9552  * PARAMETER(S):
9553  * [I] infoPtr : valid pointer to the listview structure
9554  *
9555  * RETURN:
9556  *   SUCCESS : TRUE
9557  *   FAILURE : FALSE
9558  */
9559 static BOOL LISTVIEW_DrawTrackLine(const LISTVIEW_INFO *infoPtr)
9560 {
9561     HDC hdc;
9562 
9563     if (infoPtr->xTrackLine == -1)
9564         return FALSE;
9565 
9566     if (!(hdc = GetDC(infoPtr->hwndSelf)))
9567         return FALSE;
9568     PatBlt( hdc, infoPtr->xTrackLine, infoPtr->rcList.top,
9569             1, infoPtr->rcList.bottom - infoPtr->rcList.top, DSTINVERT );
9570     ReleaseDC(infoPtr->hwndSelf, hdc);
9571     return TRUE;
9572 }
9573 
9574 /***
9575  * DESCRIPTION:
9576  * Called when an edit control should be displayed. This function is called after
9577  * we are sure that there was a single click - not a double click (this is a TIMERPROC).
9578  *
9579  * PARAMETER(S):
9580  * [I] hwnd : Handle to the listview
9581  * [I] uMsg : WM_TIMER (ignored)
9582  * [I] idEvent : The timer ID interpreted as a pointer to a DELAYED_EDIT_ITEM struct
9583  * [I] dwTimer : The elapsed time (ignored)
9584  *
9585  * RETURN:
9586  *   None.
9587  */
9588 static VOID CALLBACK LISTVIEW_DelayedEditItem(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime)
9589 {
9590     DELAYED_ITEM_EDIT *editItem = (DELAYED_ITEM_EDIT *)idEvent;
9591     LISTVIEW_INFO *infoPtr = (LISTVIEW_INFO *)GetWindowLongPtrW(hwnd, 0);
9592 
9593     KillTimer(hwnd, idEvent);
9594     editItem->fEnabled = FALSE;
9595     /* check if the item is still selected */
9596     if (infoPtr->bFocus && LISTVIEW_GetItemState(infoPtr, editItem->iItem, LVIS_SELECTED))
9597         LISTVIEW_EditLabelT(infoPtr, editItem->iItem, TRUE);
9598 }
9599 
9600 /***
9601  * DESCRIPTION:
9602  * Creates the listview control - the WM_NCCREATE phase.
9603  *
9604  * PARAMETER(S):
9605  * [I] hwnd : window handle
9606  * [I] lpcs : the create parameters
9607  *
9608  * RETURN:
9609  *   Success: TRUE
9610  *   Failure: FALSE
9611  */
9612 static LRESULT LISTVIEW_NCCreate(HWND hwnd, WPARAM wParam, const CREATESTRUCTW *lpcs)
9613 {
9614   LISTVIEW_INFO *infoPtr;
9615   LOGFONTW logFont;
9616 
9617   TRACE("(lpcs=%p)\n", lpcs);
9618 
9619   /* initialize info pointer */
9620   infoPtr = Alloc(sizeof(LISTVIEW_INFO));
9621   if (!infoPtr) return FALSE;
9622 
9623   SetWindowLongPtrW(hwnd, 0, (DWORD_PTR)infoPtr);
9624 
9625   infoPtr->hwndSelf = hwnd;
9626   infoPtr->dwStyle = lpcs->style;    /* Note: may be changed in WM_CREATE */
9627   map_style_view(infoPtr);
9628   /* determine the type of structures to use */
9629   infoPtr->hwndNotify = lpcs->hwndParent;
9630   /* infoPtr->notifyFormat will be filled in WM_CREATE */
9631 
9632   /* initialize color information  */
9633   infoPtr->clrBk = CLR_NONE;
9634   infoPtr->clrText = CLR_DEFAULT;
9635   infoPtr->clrTextBk = CLR_DEFAULT;
9636   LISTVIEW_SetBkColor(infoPtr, comctl32_color.clrWindow);
9637 #ifdef __REACTOS__
9638   infoPtr->bDefaultBkColor = TRUE;
9639 #endif
9640 
9641   /* set default values */
9642   infoPtr->nFocusedItem = -1;
9643   infoPtr->nSelectionMark = -1;
9644   infoPtr->nHotItem = -1;
9645   infoPtr->redraw = TRUE;
9646   infoPtr->bNoItemMetrics = TRUE;
9647   infoPtr->notify_mask = NOTIFY_MASK_UNMASK_ALL;
9648   infoPtr->autoSpacing = TRUE;
9649   infoPtr->iconSpacing.cx = GetSystemMetrics(SM_CXICONSPACING) - GetSystemMetrics(SM_CXICON);
9650   infoPtr->iconSpacing.cy = GetSystemMetrics(SM_CYICONSPACING) - GetSystemMetrics(SM_CYICON);
9651   infoPtr->nEditLabelItem = -1;
9652   infoPtr->nLButtonDownItem = -1;
9653   infoPtr->dwHoverTime = HOVER_DEFAULT; /* default system hover time */
9654   infoPtr->cWheelRemainder = 0;
9655   infoPtr->nMeasureItemHeight = 0;
9656   infoPtr->xTrackLine = -1;  /* no track line */
9657   infoPtr->itemEdit.fEnabled = FALSE;
9658   infoPtr->iVersion = COMCTL32_VERSION;
9659   infoPtr->colRectsDirty = FALSE;
9660 
9661   /* get default font (icon title) */
9662   SystemParametersInfoW(SPI_GETICONTITLELOGFONT, 0, &logFont, 0);
9663   infoPtr->hDefaultFont = CreateFontIndirectW(&logFont);
9664   infoPtr->hFont = infoPtr->hDefaultFont;
9665   LISTVIEW_SaveTextMetrics(infoPtr);
9666 
9667   /* allocate memory for the data structure */
9668   if (!(infoPtr->selectionRanges = ranges_create(10))) goto fail;
9669   if (!(infoPtr->hdpaItems = DPA_Create(10))) goto fail;
9670   if (!(infoPtr->hdpaItemIds = DPA_Create(10))) goto fail;
9671   if (!(infoPtr->hdpaPosX  = DPA_Create(10))) goto fail;
9672   if (!(infoPtr->hdpaPosY  = DPA_Create(10))) goto fail;
9673   if (!(infoPtr->hdpaColumns = DPA_Create(10))) goto fail;
9674 
9675   return DefWindowProcW(hwnd, WM_NCCREATE, wParam, (LPARAM)lpcs);
9676 
9677 fail:
9678     DestroyWindow(infoPtr->hwndHeader);
9679     ranges_destroy(infoPtr->selectionRanges);
9680     DPA_Destroy(infoPtr->hdpaItems);
9681     DPA_Destroy(infoPtr->hdpaItemIds);
9682     DPA_Destroy(infoPtr->hdpaPosX);
9683     DPA_Destroy(infoPtr->hdpaPosY);
9684     DPA_Destroy(infoPtr->hdpaColumns);
9685     Free(infoPtr);
9686     return FALSE;
9687 }
9688 
9689 /***
9690  * DESCRIPTION:
9691  * Creates the listview control - the WM_CREATE phase. Most of the data is
9692  * already set up in LISTVIEW_NCCreate
9693  *
9694  * PARAMETER(S):
9695  * [I] hwnd : window handle
9696  * [I] lpcs : the create parameters
9697  *
9698  * RETURN:
9699  *   Success: 0
9700  *   Failure: -1
9701  */
9702 static LRESULT LISTVIEW_Create(HWND hwnd, const CREATESTRUCTW *lpcs)
9703 {
9704   LISTVIEW_INFO *infoPtr = (LISTVIEW_INFO *)GetWindowLongPtrW(hwnd, 0);
9705 
9706   TRACE("(lpcs=%p, style=0x%08x)\n", lpcs, lpcs->style);
9707 
9708   infoPtr->dwStyle = lpcs->style;
9709   map_style_view(infoPtr);
9710 
9711   infoPtr->notifyFormat = SendMessageW(infoPtr->hwndNotify, WM_NOTIFYFORMAT,
9712                                        (WPARAM)infoPtr->hwndSelf, NF_QUERY);
9713   /* on error defaulting to ANSI notifications */
9714   if (infoPtr->notifyFormat == 0) infoPtr->notifyFormat = NFR_ANSI;
9715   TRACE("notify format=%d\n", infoPtr->notifyFormat);
9716 
9717   if ((infoPtr->uView == LV_VIEW_DETAILS) && (lpcs->style & WS_VISIBLE))
9718   {
9719     if (LISTVIEW_CreateHeader(infoPtr) < 0)  return -1;
9720   }
9721   else
9722     infoPtr->hwndHeader = 0;
9723 
9724   /* init item size to avoid division by 0 */
9725   LISTVIEW_UpdateItemSize (infoPtr);
9726   LISTVIEW_UpdateSize (infoPtr);
9727 
9728   if (infoPtr->uView == LV_VIEW_DETAILS)
9729   {
9730     if (!(LVS_NOCOLUMNHEADER & lpcs->style) && (WS_VISIBLE & lpcs->style))
9731     {
9732       ShowWindow(infoPtr->hwndHeader, SW_SHOWNORMAL);
9733     }
9734     LISTVIEW_UpdateScroll(infoPtr);
9735     /* send WM_MEASUREITEM notification */
9736     if (infoPtr->dwStyle & LVS_OWNERDRAWFIXED) notify_measureitem(infoPtr);
9737   }
9738 
9739   OpenThemeData(hwnd, themeClass);
9740 
9741   /* initialize the icon sizes */
9742   set_icon_size(&infoPtr->iconSize, infoPtr->himlNormal, infoPtr->uView != LV_VIEW_ICON);
9743   set_icon_size(&infoPtr->iconStateSize, infoPtr->himlState, TRUE);
9744   return 0;
9745 }
9746 
9747 /***
9748  * DESCRIPTION:
9749  * Destroys the listview control.
9750  *
9751  * PARAMETER(S):
9752  * [I] infoPtr : valid pointer to the listview structure
9753  *
9754  * RETURN:
9755  *   Success: 0
9756  *   Failure: -1
9757  */
9758 static LRESULT LISTVIEW_Destroy(LISTVIEW_INFO *infoPtr)
9759 {
9760     HTHEME theme = GetWindowTheme(infoPtr->hwndSelf);
9761     CloseThemeData(theme);
9762 
9763     /* delete all items */
9764     LISTVIEW_DeleteAllItems(infoPtr, TRUE);
9765 
9766     return 0;
9767 }
9768 
9769 /***
9770  * DESCRIPTION:
9771  * Enables the listview control.
9772  *
9773  * PARAMETER(S):
9774  * [I] infoPtr : valid pointer to the listview structure
9775  * [I] bEnable : specifies whether to enable or disable the window
9776  *
9777  * RETURN:
9778  *   SUCCESS : TRUE
9779  *   FAILURE : FALSE
9780  */
9781 static BOOL LISTVIEW_Enable(const LISTVIEW_INFO *infoPtr)
9782 {
9783     if (infoPtr->dwStyle & LVS_OWNERDRAWFIXED)
9784         InvalidateRect(infoPtr->hwndSelf, NULL, TRUE);
9785     return TRUE;
9786 }
9787 
9788 /***
9789  * DESCRIPTION:
9790  * Erases the background of the listview control.
9791  *
9792  * PARAMETER(S):
9793  * [I] infoPtr : valid pointer to the listview structure
9794  * [I] hdc : device context handle
9795  *
9796  * RETURN:
9797  *   SUCCESS : TRUE
9798  *   FAILURE : FALSE
9799  */
9800 static inline BOOL LISTVIEW_EraseBkgnd(const LISTVIEW_INFO *infoPtr, HDC hdc)
9801 {
9802     RECT rc;
9803 
9804     TRACE("(hdc=%p)\n", hdc);
9805 
9806     if (!GetClipBox(hdc, &rc)) return FALSE;
9807 
9808     if (infoPtr->clrBk == CLR_NONE)
9809     {
9810         if (infoPtr->dwLvExStyle & LVS_EX_TRANSPARENTBKGND)
9811             return SendMessageW(infoPtr->hwndNotify, WM_PRINTCLIENT,
9812                                 (WPARAM)hdc, PRF_ERASEBKGND);
9813         else
9814             return SendMessageW(infoPtr->hwndNotify, WM_ERASEBKGND, (WPARAM)hdc, 0);
9815     }
9816 
9817     /* for double buffered controls we need to do this during refresh */
9818     if (infoPtr->dwLvExStyle & LVS_EX_DOUBLEBUFFER) return FALSE;
9819 
9820     return LISTVIEW_FillBkgnd(infoPtr, hdc, &rc);
9821 }
9822 
9823 
9824 /***
9825  * DESCRIPTION:
9826  * Helper function for LISTVIEW_[HV]Scroll *only*.
9827  * Performs vertical/horizontal scrolling by a give amount.
9828  *
9829  * PARAMETER(S):
9830  * [I] infoPtr : valid pointer to the listview structure
9831  * [I] dx : amount of horizontal scroll
9832  * [I] dy : amount of vertical scroll
9833  */
9834 static void scroll_list(LISTVIEW_INFO *infoPtr, INT dx, INT dy)
9835 {
9836     /* now we can scroll the list */
9837     ScrollWindowEx(infoPtr->hwndSelf, dx, dy, &infoPtr->rcList,
9838 		   &infoPtr->rcList, 0, 0, SW_ERASE | SW_INVALIDATE);
9839     /* if we have focus, adjust rect */
9840     OffsetRect(&infoPtr->rcFocus, dx, dy);
9841     UpdateWindow(infoPtr->hwndSelf);
9842 }
9843 
9844 /***
9845  * DESCRIPTION:
9846  * Performs vertical scrolling.
9847  *
9848  * PARAMETER(S):
9849  * [I] infoPtr : valid pointer to the listview structure
9850  * [I] nScrollCode : scroll code
9851  * [I] nScrollDiff : units to scroll in SB_INTERNAL mode, 0 otherwise
9852  * [I] hScrollWnd  : scrollbar control window handle
9853  *
9854  * RETURN:
9855  * Zero
9856  *
9857  * NOTES:
9858  *   SB_LINEUP/SB_LINEDOWN:
9859  *        for LVS_ICON, LVS_SMALLICON is 37 by experiment
9860  *        for LVS_REPORT is 1 line
9861  *        for LVS_LIST cannot occur
9862  *
9863  */
9864 static LRESULT LISTVIEW_VScroll(LISTVIEW_INFO *infoPtr, INT nScrollCode,
9865 				INT nScrollDiff)
9866 {
9867     INT nOldScrollPos, nNewScrollPos;
9868     SCROLLINFO scrollInfo;
9869     BOOL is_an_icon;
9870 
9871     TRACE("(nScrollCode=%d(%s), nScrollDiff=%d)\n", nScrollCode,
9872 	debugscrollcode(nScrollCode), nScrollDiff);
9873 
9874     if (infoPtr->hwndEdit) SendMessageW(infoPtr->hwndEdit, WM_KILLFOCUS, 0, 0);
9875 
9876     scrollInfo.cbSize = sizeof(SCROLLINFO);
9877     scrollInfo.fMask = SIF_PAGE | SIF_POS | SIF_RANGE | SIF_TRACKPOS;
9878 
9879     is_an_icon = ((infoPtr->uView == LV_VIEW_ICON) || (infoPtr->uView == LV_VIEW_SMALLICON));
9880 
9881     if (!GetScrollInfo(infoPtr->hwndSelf, SB_VERT, &scrollInfo)) return 1;
9882 
9883     nOldScrollPos = scrollInfo.nPos;
9884     switch (nScrollCode)
9885     {
9886     case SB_INTERNAL:
9887         break;
9888 
9889     case SB_LINEUP:
9890 	nScrollDiff = (is_an_icon) ? -LISTVIEW_SCROLL_ICON_LINE_SIZE : -1;
9891         break;
9892 
9893     case SB_LINEDOWN:
9894 	nScrollDiff = (is_an_icon) ? LISTVIEW_SCROLL_ICON_LINE_SIZE : 1;
9895         break;
9896 
9897     case SB_PAGEUP:
9898 	nScrollDiff = -scrollInfo.nPage;
9899         break;
9900 
9901     case SB_PAGEDOWN:
9902 	nScrollDiff = scrollInfo.nPage;
9903         break;
9904 
9905     case SB_THUMBPOSITION:
9906     case SB_THUMBTRACK:
9907 	nScrollDiff = scrollInfo.nTrackPos - scrollInfo.nPos;
9908         break;
9909 
9910     default:
9911 	nScrollDiff = 0;
9912     }
9913 
9914     /* quit right away if pos isn't changing */
9915     if (nScrollDiff == 0) return 0;
9916 
9917     /* calculate new position, and handle overflows */
9918     nNewScrollPos = scrollInfo.nPos + nScrollDiff;
9919     if (nScrollDiff > 0) {
9920 	if (nNewScrollPos < nOldScrollPos ||
9921 	    nNewScrollPos > scrollInfo.nMax)
9922 	    nNewScrollPos = scrollInfo.nMax;
9923     } else {
9924 	if (nNewScrollPos > nOldScrollPos ||
9925 	    nNewScrollPos < scrollInfo.nMin)
9926 	    nNewScrollPos = scrollInfo.nMin;
9927     }
9928 
9929     /* set the new position, and reread in case it changed */
9930     scrollInfo.fMask = SIF_POS;
9931     scrollInfo.nPos = nNewScrollPos;
9932     nNewScrollPos = SetScrollInfo(infoPtr->hwndSelf, SB_VERT, &scrollInfo, TRUE);
9933 
9934     /* carry on only if it really changed */
9935     if (nNewScrollPos == nOldScrollPos) return 0;
9936 
9937     /* now adjust to client coordinates */
9938     nScrollDiff = nOldScrollPos - nNewScrollPos;
9939     if (infoPtr->uView == LV_VIEW_DETAILS) nScrollDiff *= infoPtr->nItemHeight;
9940 
9941     /* and scroll the window */
9942     scroll_list(infoPtr, 0, nScrollDiff);
9943 
9944     return 0;
9945 }
9946 
9947 /***
9948  * DESCRIPTION:
9949  * Performs horizontal scrolling.
9950  *
9951  * PARAMETER(S):
9952  * [I] infoPtr : valid pointer to the listview structure
9953  * [I] nScrollCode : scroll code
9954  * [I] nScrollDiff : units to scroll in SB_INTERNAL mode, 0 otherwise
9955  * [I] hScrollWnd  : scrollbar control window handle
9956  *
9957  * RETURN:
9958  * Zero
9959  *
9960  * NOTES:
9961  *   SB_LINELEFT/SB_LINERIGHT:
9962  *        for LVS_ICON, LVS_SMALLICON  1 pixel
9963  *        for LVS_REPORT is 1 pixel
9964  *        for LVS_LIST  is 1 column --> which is a 1 because the
9965  *                                      scroll is based on columns not pixels
9966  *
9967  */
9968 static LRESULT LISTVIEW_HScroll(LISTVIEW_INFO *infoPtr, INT nScrollCode,
9969                                 INT nScrollDiff)
9970 {
9971     INT nOldScrollPos, nNewScrollPos;
9972     SCROLLINFO scrollInfo;
9973     BOOL is_an_icon;
9974 
9975     TRACE("(nScrollCode=%d(%s), nScrollDiff=%d)\n", nScrollCode,
9976 	debugscrollcode(nScrollCode), nScrollDiff);
9977 
9978     if (infoPtr->hwndEdit) SendMessageW(infoPtr->hwndEdit, WM_KILLFOCUS, 0, 0);
9979 
9980     scrollInfo.cbSize = sizeof(SCROLLINFO);
9981     scrollInfo.fMask = SIF_PAGE | SIF_POS | SIF_RANGE | SIF_TRACKPOS;
9982 
9983     is_an_icon = ((infoPtr->uView == LV_VIEW_ICON) || (infoPtr->uView == LV_VIEW_SMALLICON));
9984 
9985     if (!GetScrollInfo(infoPtr->hwndSelf, SB_HORZ, &scrollInfo)) return 1;
9986 
9987     nOldScrollPos = scrollInfo.nPos;
9988 
9989     switch (nScrollCode)
9990     {
9991     case SB_INTERNAL:
9992         break;
9993 
9994     case SB_LINELEFT:
9995 	nScrollDiff = (is_an_icon) ? -LISTVIEW_SCROLL_ICON_LINE_SIZE : -1;
9996         break;
9997 
9998     case SB_LINERIGHT:
9999 	nScrollDiff = (is_an_icon) ? LISTVIEW_SCROLL_ICON_LINE_SIZE : 1;
10000         break;
10001 
10002     case SB_PAGELEFT:
10003 	nScrollDiff = -scrollInfo.nPage;
10004         break;
10005 
10006     case SB_PAGERIGHT:
10007 	nScrollDiff = scrollInfo.nPage;
10008         break;
10009 
10010     case SB_THUMBPOSITION:
10011     case SB_THUMBTRACK:
10012 	nScrollDiff = scrollInfo.nTrackPos - scrollInfo.nPos;
10013 	break;
10014 
10015     default:
10016 	nScrollDiff = 0;
10017     }
10018 
10019     /* quit right away if pos isn't changing */
10020     if (nScrollDiff == 0) return 0;
10021 
10022     /* calculate new position, and handle overflows */
10023     nNewScrollPos = scrollInfo.nPos + nScrollDiff;
10024     if (nScrollDiff > 0) {
10025 	if (nNewScrollPos < nOldScrollPos ||
10026 	    nNewScrollPos > scrollInfo.nMax)
10027 	    nNewScrollPos = scrollInfo.nMax;
10028     } else {
10029 	if (nNewScrollPos > nOldScrollPos ||
10030 	    nNewScrollPos < scrollInfo.nMin)
10031 	    nNewScrollPos = scrollInfo.nMin;
10032     }
10033 
10034     /* set the new position, and reread in case it changed */
10035     scrollInfo.fMask = SIF_POS;
10036     scrollInfo.nPos = nNewScrollPos;
10037     nNewScrollPos = SetScrollInfo(infoPtr->hwndSelf, SB_HORZ, &scrollInfo, TRUE);
10038 
10039     /* carry on only if it really changed */
10040     if (nNewScrollPos == nOldScrollPos) return 0;
10041 
10042     LISTVIEW_UpdateHeaderSize(infoPtr, nNewScrollPos);
10043 
10044     /* now adjust to client coordinates */
10045     nScrollDiff = nOldScrollPos - nNewScrollPos;
10046     if (infoPtr->uView == LV_VIEW_LIST) nScrollDiff *= infoPtr->nItemWidth;
10047 
10048     /* and scroll the window */
10049     scroll_list(infoPtr, nScrollDiff, 0);
10050 
10051     return 0;
10052 }
10053 
10054 static LRESULT LISTVIEW_MouseWheel(LISTVIEW_INFO *infoPtr, INT wheelDelta)
10055 {
10056     INT pulScrollLines = 3;
10057 
10058     TRACE("(wheelDelta=%d)\n", wheelDelta);
10059 
10060     switch(infoPtr->uView)
10061     {
10062     case LV_VIEW_ICON:
10063     case LV_VIEW_SMALLICON:
10064        /*
10065         *  listview should be scrolled by a multiple of 37 dependently on its dimension or its visible item number
10066         *  should be fixed in the future.
10067         */
10068         LISTVIEW_VScroll(infoPtr, SB_INTERNAL, (wheelDelta > 0) ?
10069                 -LISTVIEW_SCROLL_ICON_LINE_SIZE : LISTVIEW_SCROLL_ICON_LINE_SIZE);
10070         break;
10071 
10072     case LV_VIEW_DETAILS:
10073         SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
10074 
10075         /* if scrolling changes direction, ignore left overs */
10076         if ((wheelDelta < 0 && infoPtr->cWheelRemainder < 0) ||
10077             (wheelDelta > 0 && infoPtr->cWheelRemainder > 0))
10078             infoPtr->cWheelRemainder += wheelDelta;
10079         else
10080             infoPtr->cWheelRemainder = wheelDelta;
10081         if (infoPtr->cWheelRemainder && pulScrollLines)
10082         {
10083             int cLineScroll;
10084             pulScrollLines = min((UINT)LISTVIEW_GetCountPerColumn(infoPtr), pulScrollLines);
10085             cLineScroll = pulScrollLines * infoPtr->cWheelRemainder / WHEEL_DELTA;
10086             infoPtr->cWheelRemainder -= WHEEL_DELTA * cLineScroll / pulScrollLines;
10087             LISTVIEW_VScroll(infoPtr, SB_INTERNAL, -cLineScroll);
10088         }
10089         break;
10090 
10091     case LV_VIEW_LIST:
10092         LISTVIEW_HScroll(infoPtr, (wheelDelta > 0) ? SB_LINELEFT : SB_LINERIGHT, 0);
10093         break;
10094     }
10095     return 0;
10096 }
10097 
10098 /***
10099  * DESCRIPTION:
10100  * ???
10101  *
10102  * PARAMETER(S):
10103  * [I] infoPtr : valid pointer to the listview structure
10104  * [I] nVirtualKey : virtual key
10105  * [I] lKeyData : key data
10106  *
10107  * RETURN:
10108  * Zero
10109  */
10110 static LRESULT LISTVIEW_KeyDown(LISTVIEW_INFO *infoPtr, INT nVirtualKey, LONG lKeyData)
10111 {
10112   HWND hwndSelf = infoPtr->hwndSelf;
10113   INT nItem = -1;
10114   NMLVKEYDOWN nmKeyDown;
10115 
10116   TRACE("(nVirtualKey=%d, lKeyData=%d)\n", nVirtualKey, lKeyData);
10117 
10118   /* send LVN_KEYDOWN notification */
10119   nmKeyDown.wVKey = nVirtualKey;
10120   nmKeyDown.flags = 0;
10121   notify_hdr(infoPtr, LVN_KEYDOWN, &nmKeyDown.hdr);
10122   if (!IsWindow(hwndSelf))
10123     return 0;
10124 
10125   switch (nVirtualKey)
10126   {
10127   case VK_SPACE:
10128     nItem = infoPtr->nFocusedItem;
10129     if (infoPtr->dwLvExStyle & LVS_EX_CHECKBOXES)
10130         toggle_checkbox_state(infoPtr, infoPtr->nFocusedItem);
10131     break;
10132 
10133   case VK_RETURN:
10134     if ((infoPtr->nItemCount > 0) && (infoPtr->nFocusedItem != -1))
10135     {
10136         if (!notify(infoPtr, NM_RETURN)) return 0;
10137         if (!notify(infoPtr, LVN_ITEMACTIVATE)) return 0;
10138     }
10139     break;
10140 
10141   case VK_HOME:
10142     if (infoPtr->nItemCount > 0)
10143       nItem = 0;
10144     break;
10145 
10146   case VK_END:
10147     if (infoPtr->nItemCount > 0)
10148       nItem = infoPtr->nItemCount - 1;
10149     break;
10150 
10151   case VK_LEFT:
10152     nItem = LISTVIEW_GetNextItem(infoPtr, infoPtr->nFocusedItem, LVNI_TOLEFT);
10153     break;
10154 
10155   case VK_UP:
10156     nItem = LISTVIEW_GetNextItem(infoPtr, infoPtr->nFocusedItem, LVNI_ABOVE);
10157     break;
10158 
10159   case VK_RIGHT:
10160     nItem = LISTVIEW_GetNextItem(infoPtr, infoPtr->nFocusedItem, LVNI_TORIGHT);
10161     break;
10162 
10163   case VK_DOWN:
10164     nItem = LISTVIEW_GetNextItem(infoPtr, infoPtr->nFocusedItem, LVNI_BELOW);
10165     break;
10166 
10167   case VK_PRIOR:
10168     if (infoPtr->uView == LV_VIEW_DETAILS)
10169     {
10170       INT topidx = LISTVIEW_GetTopIndex(infoPtr);
10171       if (infoPtr->nFocusedItem == topidx)
10172         nItem = topidx - LISTVIEW_GetCountPerColumn(infoPtr) + 1;
10173       else
10174         nItem = topidx;
10175     }
10176     else
10177       nItem = infoPtr->nFocusedItem - LISTVIEW_GetCountPerColumn(infoPtr)
10178                                     * LISTVIEW_GetCountPerRow(infoPtr);
10179     if(nItem < 0) nItem = 0;
10180     break;
10181 
10182   case VK_NEXT:
10183     if (infoPtr->uView == LV_VIEW_DETAILS)
10184     {
10185       INT topidx = LISTVIEW_GetTopIndex(infoPtr);
10186       INT cnt = LISTVIEW_GetCountPerColumn(infoPtr);
10187       if (infoPtr->nFocusedItem == topidx + cnt - 1)
10188         nItem = infoPtr->nFocusedItem + cnt - 1;
10189       else
10190         nItem = topidx + cnt - 1;
10191     }
10192     else
10193       nItem = infoPtr->nFocusedItem + LISTVIEW_GetCountPerColumn(infoPtr)
10194                                     * LISTVIEW_GetCountPerRow(infoPtr);
10195     if(nItem >= infoPtr->nItemCount) nItem = infoPtr->nItemCount - 1;
10196     break;
10197   }
10198 
10199   if ((nItem != -1) && (nItem != infoPtr->nFocusedItem || nVirtualKey == VK_SPACE))
10200       LISTVIEW_KeySelection(infoPtr, nItem, nVirtualKey == VK_SPACE);
10201 
10202   return 0;
10203 }
10204 
10205 /***
10206  * DESCRIPTION:
10207  * Kills the focus.
10208  *
10209  * PARAMETER(S):
10210  * [I] infoPtr : valid pointer to the listview structure
10211  *
10212  * RETURN:
10213  * Zero
10214  */
10215 static LRESULT LISTVIEW_KillFocus(LISTVIEW_INFO *infoPtr)
10216 {
10217     TRACE("()\n");
10218 
10219     /* drop any left over scroll amount */
10220     infoPtr->cWheelRemainder = 0;
10221 
10222     /* if we did not have the focus, there's nothing more to do */
10223     if (!infoPtr->bFocus) return 0;
10224 
10225     /* send NM_KILLFOCUS notification */
10226     if (!notify(infoPtr, NM_KILLFOCUS)) return 0;
10227 
10228     /* if we have a focus rectangle, get rid of it */
10229     LISTVIEW_ShowFocusRect(infoPtr, FALSE);
10230 
10231     /* if have a marquee selection, stop it */
10232     if (infoPtr->bMarqueeSelect)
10233     {
10234         /* Remove the marquee rectangle and release our mouse capture */
10235         LISTVIEW_InvalidateRect(infoPtr, &infoPtr->marqueeRect);
10236         ReleaseCapture();
10237 
10238         SetRectEmpty(&infoPtr->marqueeRect);
10239 
10240         infoPtr->bMarqueeSelect = FALSE;
10241         infoPtr->bScrolling = FALSE;
10242         KillTimer(infoPtr->hwndSelf, (UINT_PTR) infoPtr);
10243     }
10244 
10245     /* set window focus flag */
10246     infoPtr->bFocus = FALSE;
10247 
10248     /* invalidate the selected items before resetting focus flag */
10249     LISTVIEW_InvalidateSelectedItems(infoPtr);
10250 
10251     return 0;
10252 }
10253 
10254 /***
10255  * DESCRIPTION:
10256  * Processes double click messages (left mouse button).
10257  *
10258  * PARAMETER(S):
10259  * [I] infoPtr : valid pointer to the listview structure
10260  * [I] wKey : key flag
10261  * [I] x,y : mouse coordinate
10262  *
10263  * RETURN:
10264  * Zero
10265  */
10266 static LRESULT LISTVIEW_LButtonDblClk(LISTVIEW_INFO *infoPtr, WORD wKey, INT x, INT y)
10267 {
10268     LVHITTESTINFO htInfo;
10269 
10270     TRACE("(key=%hu, X=%u, Y=%u)\n", wKey, x, y);
10271 
10272     /* Cancel the item edition if any */
10273     if (infoPtr->itemEdit.fEnabled)
10274     {
10275       KillTimer(infoPtr->hwndSelf, (UINT_PTR)&infoPtr->itemEdit);
10276       infoPtr->itemEdit.fEnabled = FALSE;
10277     }
10278 
10279     /* send NM_RELEASEDCAPTURE notification */
10280     if (!notify(infoPtr, NM_RELEASEDCAPTURE)) return 0;
10281 
10282     htInfo.pt.x = x;
10283     htInfo.pt.y = y;
10284 
10285     /* send NM_DBLCLK notification */
10286     LISTVIEW_HitTest(infoPtr, &htInfo, TRUE, FALSE);
10287     if (!notify_click(infoPtr, NM_DBLCLK, &htInfo)) return 0;
10288 
10289     /* To send the LVN_ITEMACTIVATE, it must be on an Item */
10290     if(htInfo.iItem != -1) notify_itemactivate(infoPtr,&htInfo);
10291 
10292     return 0;
10293 }
10294 
10295 static LRESULT LISTVIEW_TrackMouse(const LISTVIEW_INFO *infoPtr, POINT pt)
10296 {
10297     MSG msg;
10298     RECT r;
10299 
10300     r.top = r.bottom = pt.y;
10301     r.left = r.right = pt.x;
10302 
10303     InflateRect(&r, GetSystemMetrics(SM_CXDRAG), GetSystemMetrics(SM_CYDRAG));
10304 
10305     SetCapture(infoPtr->hwndSelf);
10306 
10307     while (1)
10308     {
10309 	if (PeekMessageW(&msg, 0, 0, 0, PM_REMOVE | PM_NOYIELD))
10310 	{
10311 	    if (msg.message == WM_MOUSEMOVE)
10312 	    {
10313 		pt.x = (short)LOWORD(msg.lParam);
10314 		pt.y = (short)HIWORD(msg.lParam);
10315 		if (PtInRect(&r, pt))
10316 		    continue;
10317 		else
10318 		{
10319 		    ReleaseCapture();
10320 		    return 1;
10321 		}
10322 	    }
10323 	    else if (msg.message >= WM_LBUTTONDOWN &&
10324 		     msg.message <= WM_RBUTTONDBLCLK)
10325 	    {
10326 		break;
10327 	    }
10328 
10329 	    DispatchMessageW(&msg);
10330 	}
10331 
10332 	if (GetCapture() != infoPtr->hwndSelf)
10333 	    return 0;
10334     }
10335 
10336     ReleaseCapture();
10337     return 0;
10338 }
10339 
10340 
10341 /***
10342  * DESCRIPTION:
10343  * Processes mouse down messages (left mouse button).
10344  *
10345  * PARAMETERS:
10346  *   infoPtr  [I ] valid pointer to the listview structure
10347  *   wKey     [I ] key flag
10348  *   x,y      [I ] mouse coordinate
10349  *
10350  * RETURN:
10351  *   Zero
10352  */
10353 static LRESULT LISTVIEW_LButtonDown(LISTVIEW_INFO *infoPtr, WORD wKey, INT x, INT y)
10354 {
10355   LVHITTESTINFO lvHitTestInfo;
10356   static BOOL bGroupSelect = TRUE;
10357   POINT pt = { x, y };
10358   INT nItem;
10359 
10360   TRACE("(key=%hu, X=%u, Y=%u)\n", wKey, x, y);
10361 
10362   /* send NM_RELEASEDCAPTURE notification */
10363   if (!notify(infoPtr, NM_RELEASEDCAPTURE)) return 0;
10364 
10365   /* set left button down flag and record the click position */
10366   infoPtr->bLButtonDown = TRUE;
10367   infoPtr->ptClickPos = pt;
10368   infoPtr->bDragging = FALSE;
10369   infoPtr->bMarqueeSelect = FALSE;
10370   infoPtr->bScrolling = FALSE;
10371 
10372   lvHitTestInfo.pt.x = x;
10373   lvHitTestInfo.pt.y = y;
10374 
10375   nItem = LISTVIEW_HitTest(infoPtr, &lvHitTestInfo, TRUE, TRUE);
10376   TRACE("at %s, nItem=%d\n", wine_dbgstr_point(&pt), nItem);
10377   if ((nItem >= 0) && (nItem < infoPtr->nItemCount))
10378   {
10379     if ((infoPtr->dwLvExStyle & LVS_EX_CHECKBOXES) && (lvHitTestInfo.flags & LVHT_ONITEMSTATEICON))
10380     {
10381         notify_click(infoPtr, NM_CLICK, &lvHitTestInfo);
10382         toggle_checkbox_state(infoPtr, nItem);
10383         infoPtr->bLButtonDown = FALSE;
10384         return 0;
10385     }
10386 
10387     if (infoPtr->dwStyle & LVS_SINGLESEL)
10388     {
10389       if (LISTVIEW_GetItemState(infoPtr, nItem, LVIS_SELECTED))
10390         infoPtr->nEditLabelItem = nItem;
10391       else
10392         LISTVIEW_SetSelection(infoPtr, nItem);
10393     }
10394     else
10395     {
10396       if ((wKey & MK_CONTROL) && (wKey & MK_SHIFT))
10397       {
10398         if (bGroupSelect)
10399 	{
10400           if (!LISTVIEW_AddGroupSelection(infoPtr, nItem)) return 0;
10401     	  LISTVIEW_SetItemFocus(infoPtr, nItem);
10402           infoPtr->nSelectionMark = nItem;
10403 	}
10404         else
10405 	{
10406           LVITEMW item;
10407 
10408 	  item.state = LVIS_SELECTED | LVIS_FOCUSED;
10409 	  item.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
10410 
10411 	  LISTVIEW_SetItemState(infoPtr,nItem,&item);
10412 	  infoPtr->nSelectionMark = nItem;
10413 	}
10414       }
10415       else if (wKey & MK_CONTROL)
10416       {
10417         LVITEMW item;
10418 
10419 	bGroupSelect = (LISTVIEW_GetItemState(infoPtr, nItem, LVIS_SELECTED) == 0);
10420 
10421 	item.state = (bGroupSelect ? LVIS_SELECTED : 0) | LVIS_FOCUSED;
10422         item.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
10423 	LISTVIEW_SetItemState(infoPtr, nItem, &item);
10424         infoPtr->nSelectionMark = nItem;
10425       }
10426       else  if (wKey & MK_SHIFT)
10427       {
10428         LISTVIEW_SetGroupSelection(infoPtr, nItem);
10429       }
10430       else
10431       {
10432 	if (LISTVIEW_GetItemState(infoPtr, nItem, LVIS_SELECTED))
10433 	{
10434 	  infoPtr->nEditLabelItem = nItem;
10435 	  infoPtr->nLButtonDownItem = nItem;
10436 
10437           LISTVIEW_SetItemFocus(infoPtr, nItem);
10438 	}
10439 	else
10440 	  /* set selection (clears other pre-existing selections) */
10441 	  LISTVIEW_SetSelection(infoPtr, nItem);
10442       }
10443     }
10444 
10445     if (!infoPtr->bFocus)
10446         SetFocus(infoPtr->hwndSelf);
10447 
10448     if (infoPtr->dwLvExStyle & LVS_EX_ONECLICKACTIVATE)
10449         if(lvHitTestInfo.iItem != -1) notify_itemactivate(infoPtr,&lvHitTestInfo);
10450   }
10451   else
10452   {
10453     if (!infoPtr->bFocus)
10454         SetFocus(infoPtr->hwndSelf);
10455 
10456     /* remove all selections */
10457     if (!(wKey & MK_CONTROL) && !(wKey & MK_SHIFT))
10458         LISTVIEW_DeselectAll(infoPtr);
10459     ReleaseCapture();
10460   }
10461 
10462   return 0;
10463 }
10464 
10465 /***
10466  * DESCRIPTION:
10467  * Processes mouse up messages (left mouse button).
10468  *
10469  * PARAMETERS:
10470  *   infoPtr [I ] valid pointer to the listview structure
10471  *   wKey    [I ] key flag
10472  *   x,y     [I ] mouse coordinate
10473  *
10474  * RETURN:
10475  *   Zero
10476  */
10477 static LRESULT LISTVIEW_LButtonUp(LISTVIEW_INFO *infoPtr, WORD wKey, INT x, INT y)
10478 {
10479     LVHITTESTINFO lvHitTestInfo;
10480 
10481     TRACE("(key=%hu, X=%u, Y=%u)\n", wKey, x, y);
10482 
10483     if (!infoPtr->bLButtonDown) return 0;
10484 
10485     lvHitTestInfo.pt.x = x;
10486     lvHitTestInfo.pt.y = y;
10487 
10488     /* send NM_CLICK notification */
10489     LISTVIEW_HitTest(infoPtr, &lvHitTestInfo, TRUE, FALSE);
10490     if (!notify_click(infoPtr, NM_CLICK, &lvHitTestInfo)) return 0;
10491 
10492     /* set left button flag */
10493     infoPtr->bLButtonDown = FALSE;
10494 
10495     /* set a single selection, reset others */
10496     if(lvHitTestInfo.iItem == infoPtr->nLButtonDownItem && lvHitTestInfo.iItem != -1)
10497         LISTVIEW_SetSelection(infoPtr, infoPtr->nLButtonDownItem);
10498     infoPtr->nLButtonDownItem = -1;
10499 
10500     if (infoPtr->bDragging || infoPtr->bMarqueeSelect)
10501     {
10502         /* Remove the marquee rectangle and release our mouse capture */
10503         if (infoPtr->bMarqueeSelect)
10504         {
10505             LISTVIEW_InvalidateRect(infoPtr, &infoPtr->marqueeDrawRect);
10506             ReleaseCapture();
10507         }
10508 
10509         SetRectEmpty(&infoPtr->marqueeRect);
10510         SetRectEmpty(&infoPtr->marqueeDrawRect);
10511 
10512         infoPtr->bDragging = FALSE;
10513         infoPtr->bMarqueeSelect = FALSE;
10514         infoPtr->bScrolling = FALSE;
10515 
10516         KillTimer(infoPtr->hwndSelf, (UINT_PTR) infoPtr);
10517         return 0;
10518     }
10519 
10520     /* if we clicked on a selected item, edit the label */
10521     if(lvHitTestInfo.iItem == infoPtr->nEditLabelItem && (lvHitTestInfo.flags & LVHT_ONITEMLABEL))
10522     {
10523         /* we want to make sure the user doesn't want to do a double click. So we will
10524          * delay the edit. WM_LBUTTONDBLCLICK will cancel the timer
10525          */
10526         infoPtr->itemEdit.fEnabled = TRUE;
10527         infoPtr->itemEdit.iItem = lvHitTestInfo.iItem;
10528         SetTimer(infoPtr->hwndSelf,
10529             (UINT_PTR)&infoPtr->itemEdit,
10530             GetDoubleClickTime(),
10531             LISTVIEW_DelayedEditItem);
10532     }
10533 
10534     return 0;
10535 }
10536 
10537 /***
10538  * DESCRIPTION:
10539  * Destroys the listview control (called after WM_DESTROY).
10540  *
10541  * PARAMETER(S):
10542  * [I] infoPtr : valid pointer to the listview structure
10543  *
10544  * RETURN:
10545  * Zero
10546  */
10547 static LRESULT LISTVIEW_NCDestroy(LISTVIEW_INFO *infoPtr)
10548 {
10549   INT i;
10550 
10551   TRACE("()\n");
10552 
10553   /* destroy data structure */
10554   DPA_Destroy(infoPtr->hdpaItems);
10555   DPA_Destroy(infoPtr->hdpaItemIds);
10556   DPA_Destroy(infoPtr->hdpaPosX);
10557   DPA_Destroy(infoPtr->hdpaPosY);
10558   /* columns */
10559   for (i = 0; i < DPA_GetPtrCount(infoPtr->hdpaColumns); i++)
10560       Free(DPA_GetPtr(infoPtr->hdpaColumns, i));
10561   DPA_Destroy(infoPtr->hdpaColumns);
10562   ranges_destroy(infoPtr->selectionRanges);
10563 
10564   /* destroy image lists */
10565   if (!(infoPtr->dwStyle & LVS_SHAREIMAGELISTS))
10566   {
10567       ImageList_Destroy(infoPtr->himlNormal);
10568       ImageList_Destroy(infoPtr->himlSmall);
10569       ImageList_Destroy(infoPtr->himlState);
10570   }
10571 
10572   /* destroy font, bkgnd brush */
10573   infoPtr->hFont = 0;
10574   if (infoPtr->hDefaultFont) DeleteObject(infoPtr->hDefaultFont);
10575   if (infoPtr->clrBk != CLR_NONE) DeleteObject(infoPtr->hBkBrush);
10576 
10577   SetWindowLongPtrW(infoPtr->hwndSelf, 0, 0);
10578 
10579   /* free listview info pointer*/
10580   Free(infoPtr);
10581 
10582   return 0;
10583 }
10584 
10585 /***
10586  * DESCRIPTION:
10587  * Handles notifications.
10588  *
10589  * PARAMETER(S):
10590  * [I] infoPtr : valid pointer to the listview structure
10591  * [I] lpnmhdr : notification information
10592  *
10593  * RETURN:
10594  * Zero
10595  */
10596 static LRESULT LISTVIEW_Notify(LISTVIEW_INFO *infoPtr, NMHDR *lpnmhdr)
10597 {
10598     NMHEADERW *lpnmh;
10599 
10600     TRACE("(lpnmhdr=%p)\n", lpnmhdr);
10601 
10602     if (!lpnmhdr || lpnmhdr->hwndFrom != infoPtr->hwndHeader) return 0;
10603 
10604     /* remember: HDN_LAST < HDN_FIRST */
10605     if (lpnmhdr->code > HDN_FIRST || lpnmhdr->code < HDN_LAST) return 0;
10606     lpnmh = (NMHEADERW *)lpnmhdr;
10607 
10608     if (lpnmh->iItem < 0 || lpnmh->iItem >= DPA_GetPtrCount(infoPtr->hdpaColumns)) return 0;
10609 
10610     switch (lpnmhdr->code)
10611     {
10612 	case HDN_TRACKW:
10613 	case HDN_TRACKA:
10614 	{
10615 	    COLUMN_INFO *lpColumnInfo;
10616 	    POINT ptOrigin;
10617 	    INT x;
10618 
10619 	    if (!lpnmh->pitem || !(lpnmh->pitem->mask & HDI_WIDTH))
10620 		break;
10621 
10622             /* remove the old line (if any) */
10623             LISTVIEW_DrawTrackLine(infoPtr);
10624 
10625             /* compute & draw the new line */
10626             lpColumnInfo = LISTVIEW_GetColumnInfo(infoPtr, lpnmh->iItem);
10627             x = lpColumnInfo->rcHeader.left + lpnmh->pitem->cxy;
10628             LISTVIEW_GetOrigin(infoPtr, &ptOrigin);
10629             infoPtr->xTrackLine = x + ptOrigin.x;
10630             LISTVIEW_DrawTrackLine(infoPtr);
10631             return notify_forward_header(infoPtr, lpnmh);
10632 	}
10633 
10634 	case HDN_ENDTRACKA:
10635 	case HDN_ENDTRACKW:
10636 	    /* remove the track line (if any) */
10637 	    LISTVIEW_DrawTrackLine(infoPtr);
10638 	    infoPtr->xTrackLine = -1;
10639             return notify_forward_header(infoPtr, lpnmh);
10640 
10641         case HDN_BEGINDRAG:
10642             if ((infoPtr->dwLvExStyle & LVS_EX_HEADERDRAGDROP) == 0) return 1;
10643             return notify_forward_header(infoPtr, lpnmh);
10644 
10645         case HDN_ENDDRAG:
10646             infoPtr->colRectsDirty = TRUE;
10647             LISTVIEW_InvalidateList(infoPtr);
10648             return notify_forward_header(infoPtr, lpnmh);
10649 
10650 	case HDN_ITEMCHANGEDW:
10651 	case HDN_ITEMCHANGEDA:
10652 	{
10653 	    COLUMN_INFO *lpColumnInfo;
10654 	    HDITEMW hdi;
10655 	    INT dx, cxy;
10656 
10657 	    if (!lpnmh->pitem || !(lpnmh->pitem->mask & HDI_WIDTH))
10658 	    {
10659 		hdi.mask = HDI_WIDTH;
10660 		if (!SendMessageW(infoPtr->hwndHeader, HDM_GETITEMW, lpnmh->iItem, (LPARAM)&hdi)) return 0;
10661 		cxy = hdi.cxy;
10662 	    }
10663 	    else
10664 		cxy = lpnmh->pitem->cxy;
10665 
10666 	    /* determine how much we change since the last know position */
10667 	    lpColumnInfo = LISTVIEW_GetColumnInfo(infoPtr, lpnmh->iItem);
10668 	    dx = cxy - (lpColumnInfo->rcHeader.right - lpColumnInfo->rcHeader.left);
10669 	    if (dx != 0)
10670 	    {
10671 		lpColumnInfo->rcHeader.right += dx;
10672 
10673 		hdi.mask = HDI_ORDER;
10674 		SendMessageW(infoPtr->hwndHeader, HDM_GETITEMW, lpnmh->iItem, (LPARAM)&hdi);
10675 
10676 		/* not the rightmost one */
10677 		if (hdi.iOrder + 1 < DPA_GetPtrCount(infoPtr->hdpaColumns))
10678 		{
10679 		    INT nIndex = SendMessageW(infoPtr->hwndHeader, HDM_ORDERTOINDEX,
10680 					      hdi.iOrder + 1, 0);
10681 		    LISTVIEW_ScrollColumns(infoPtr, nIndex, dx);
10682 		}
10683 		else
10684 		{
10685 		    /* only needs to update the scrolls */
10686 		    infoPtr->nItemWidth += dx;
10687 		    LISTVIEW_UpdateScroll(infoPtr);
10688 		}
10689 		LISTVIEW_UpdateItemSize(infoPtr);
10690 		if (infoPtr->uView == LV_VIEW_DETAILS && is_redrawing(infoPtr))
10691 		{
10692 		    POINT ptOrigin;
10693 		    RECT rcCol = lpColumnInfo->rcHeader;
10694 
10695 		    LISTVIEW_GetOrigin(infoPtr, &ptOrigin);
10696 		    OffsetRect(&rcCol, ptOrigin.x, 0);
10697 
10698 		    rcCol.top = infoPtr->rcList.top;
10699 		    rcCol.bottom = infoPtr->rcList.bottom;
10700 
10701 		    /* resizing left-aligned columns leaves most of the left side untouched */
10702 		    if ((lpColumnInfo->fmt & LVCFMT_JUSTIFYMASK) == LVCFMT_LEFT)
10703 		    {
10704 			INT nMaxDirty = infoPtr->nEllipsisWidth + infoPtr->ntmMaxCharWidth;
10705 			if (dx > 0)
10706 			    nMaxDirty += dx;
10707 			rcCol.left = max (rcCol.left, rcCol.right - nMaxDirty);
10708 		    }
10709 
10710 		    /* when shrinking the last column clear the now unused field */
10711 		    if (hdi.iOrder == DPA_GetPtrCount(infoPtr->hdpaColumns) - 1)
10712 		    {
10713 		        RECT right;
10714 
10715 		        rcCol.right -= dx;
10716 
10717 		        /* deal with right from rightmost column area */
10718 		        right.left = rcCol.right;
10719 		        right.top  = rcCol.top;
10720 		        right.bottom = rcCol.bottom;
10721 		        right.right = infoPtr->rcList.right;
10722 
10723 		        LISTVIEW_InvalidateRect(infoPtr, &right);
10724 		    }
10725 
10726 		    LISTVIEW_InvalidateRect(infoPtr, &rcCol);
10727 		}
10728 	    }
10729 	    break;
10730         }
10731 
10732 	case HDN_ITEMCLICKW:
10733 	case HDN_ITEMCLICKA:
10734 	{
10735             /* Handle sorting by Header Column */
10736             NMLISTVIEW nmlv;
10737 
10738             ZeroMemory(&nmlv, sizeof(NMLISTVIEW));
10739             nmlv.iItem = -1;
10740             nmlv.iSubItem = lpnmh->iItem;
10741             notify_listview(infoPtr, LVN_COLUMNCLICK, &nmlv);
10742             return notify_forward_header(infoPtr, lpnmh);
10743         }
10744 
10745 	case HDN_DIVIDERDBLCLICKW:
10746 	case HDN_DIVIDERDBLCLICKA:
10747             /* FIXME: for LVS_EX_HEADERINALLVIEWS and not LV_VIEW_DETAILS
10748                       we should use LVSCW_AUTOSIZE_USEHEADER, helper rework or
10749                       split needed for that */
10750             LISTVIEW_SetColumnWidth(infoPtr, lpnmh->iItem, LVSCW_AUTOSIZE);
10751             return notify_forward_header(infoPtr, lpnmh);
10752     }
10753     return 0;
10754 }
10755 
10756 /***
10757  * DESCRIPTION:
10758  * Paint non-client area of control.
10759  *
10760  * PARAMETER(S):
10761  * [I] infoPtr : valid pointer to the listview structureof the sender
10762  * [I] region : update region
10763  *
10764  * RETURN:
10765  *  TRUE  - frame was painted
10766  *  FALSE - call default window proc
10767  */
10768 static BOOL LISTVIEW_NCPaint(const LISTVIEW_INFO *infoPtr, HRGN region)
10769 {
10770     HTHEME theme = GetWindowTheme (infoPtr->hwndSelf);
10771     HDC dc;
10772     RECT r;
10773     HRGN cliprgn;
10774     int cxEdge = GetSystemMetrics (SM_CXEDGE),
10775         cyEdge = GetSystemMetrics (SM_CYEDGE);
10776 
10777     if (!theme)
10778        return DefWindowProcW (infoPtr->hwndSelf, WM_NCPAINT, (WPARAM)region, 0);
10779 
10780     GetWindowRect(infoPtr->hwndSelf, &r);
10781 
10782     cliprgn = CreateRectRgn (r.left + cxEdge, r.top + cyEdge,
10783         r.right - cxEdge, r.bottom - cyEdge);
10784     if (region != (HRGN)1)
10785         CombineRgn (cliprgn, cliprgn, region, RGN_AND);
10786     OffsetRect(&r, -r.left, -r.top);
10787 
10788 #ifdef __REACTOS__ /* r73789 */
10789     dc = GetWindowDC(infoPtr->hwndSelf);
10790     /* Exclude client part */
10791     ExcludeClipRect(dc, r.left + cxEdge, r.top + cyEdge,
10792         r.right - cxEdge, r.bottom -cyEdge);
10793 #else
10794     dc = GetDCEx(infoPtr->hwndSelf, region, DCX_WINDOW|DCX_INTERSECTRGN);
10795     OffsetRect(&r, -r.left, -r.top);
10796 #endif
10797 
10798     if (IsThemeBackgroundPartiallyTransparent (theme, 0, 0))
10799         DrawThemeParentBackground(infoPtr->hwndSelf, dc, &r);
10800     DrawThemeBackground (theme, dc, 0, 0, &r, 0);
10801     ReleaseDC(infoPtr->hwndSelf, dc);
10802 
10803     /* Call default proc to get the scrollbars etc. painted */
10804     DefWindowProcW (infoPtr->hwndSelf, WM_NCPAINT, (WPARAM)cliprgn, 0);
10805 
10806     return FALSE;
10807 }
10808 
10809 /***
10810  * DESCRIPTION:
10811  * Determines the type of structure to use.
10812  *
10813  * PARAMETER(S):
10814  * [I] infoPtr : valid pointer to the listview structureof the sender
10815  * [I] hwndFrom : listview window handle
10816  * [I] nCommand : command specifying the nature of the WM_NOTIFYFORMAT
10817  *
10818  * RETURN:
10819  * Zero
10820  */
10821 static LRESULT LISTVIEW_NotifyFormat(LISTVIEW_INFO *infoPtr, HWND hwndFrom, INT nCommand)
10822 {
10823     TRACE("(hwndFrom=%p, nCommand=%d)\n", hwndFrom, nCommand);
10824 
10825     if (nCommand == NF_REQUERY)
10826         infoPtr->notifyFormat = SendMessageW(infoPtr->hwndNotify, WM_NOTIFYFORMAT, (WPARAM)infoPtr->hwndSelf, NF_QUERY);
10827 
10828     return infoPtr->notifyFormat;
10829 }
10830 
10831 /***
10832  * DESCRIPTION:
10833  * Paints/Repaints the listview control. Internal use.
10834  *
10835  * PARAMETER(S):
10836  * [I] infoPtr : valid pointer to the listview structure
10837  * [I] hdc : device context handle
10838  *
10839  * RETURN:
10840  * Zero
10841  */
10842 static LRESULT LISTVIEW_Paint(LISTVIEW_INFO *infoPtr, HDC hdc)
10843 {
10844     TRACE("(hdc=%p)\n", hdc);
10845 
10846     if (infoPtr->bNoItemMetrics && infoPtr->nItemCount)
10847     {
10848 	infoPtr->bNoItemMetrics = FALSE;
10849 	LISTVIEW_UpdateItemSize(infoPtr);
10850 	if (infoPtr->uView == LV_VIEW_ICON || infoPtr->uView == LV_VIEW_SMALLICON)
10851 	    LISTVIEW_Arrange(infoPtr, LVA_DEFAULT);
10852 	LISTVIEW_UpdateScroll(infoPtr);
10853     }
10854 
10855     if (infoPtr->hwndHeader)  UpdateWindow(infoPtr->hwndHeader);
10856 
10857     if (hdc)
10858         LISTVIEW_Refresh(infoPtr, hdc, NULL);
10859     else
10860     {
10861 	PAINTSTRUCT ps;
10862 
10863 	hdc = BeginPaint(infoPtr->hwndSelf, &ps);
10864 	if (!hdc) return 1;
10865 	LISTVIEW_Refresh(infoPtr, hdc, ps.fErase ? &ps.rcPaint : NULL);
10866 	EndPaint(infoPtr->hwndSelf, &ps);
10867     }
10868 
10869     return 0;
10870 }
10871 
10872 /***
10873  * DESCRIPTION:
10874  * Paints/Repaints the listview control, WM_PAINT handler.
10875  *
10876  * PARAMETER(S):
10877  * [I] infoPtr : valid pointer to the listview structure
10878  * [I] hdc : device context handle
10879  *
10880  * RETURN:
10881  * Zero
10882  */
10883 static inline LRESULT LISTVIEW_WMPaint(LISTVIEW_INFO *infoPtr, HDC hdc)
10884 {
10885     TRACE("(hdc=%p)\n", hdc);
10886 
10887     if (!is_redrawing(infoPtr))
10888         return DefWindowProcW (infoPtr->hwndSelf, WM_PAINT, (WPARAM)hdc, 0);
10889 
10890     return LISTVIEW_Paint(infoPtr, hdc);
10891 }
10892 
10893 /***
10894  * DESCRIPTION:
10895  * Paints/Repaints the listview control.
10896  *
10897  * PARAMETER(S):
10898  * [I] infoPtr : valid pointer to the listview structure
10899  * [I] hdc : device context handle
10900  * [I] options : drawing options
10901  *
10902  * RETURN:
10903  * Zero
10904  */
10905 static LRESULT LISTVIEW_PrintClient(LISTVIEW_INFO *infoPtr, HDC hdc, DWORD options)
10906 {
10907     if ((options & PRF_CHECKVISIBLE) && !IsWindowVisible(infoPtr->hwndSelf))
10908         return 0;
10909 
10910     if (options & ~(PRF_ERASEBKGND|PRF_CLIENT))
10911         FIXME("(hdc=%p options=0x%08x) partial stub\n", hdc, options);
10912 
10913     if (options & PRF_ERASEBKGND)
10914         LISTVIEW_EraseBkgnd(infoPtr, hdc);
10915 
10916     if (options & PRF_CLIENT)
10917         LISTVIEW_Paint(infoPtr, hdc);
10918 
10919     return 0;
10920 }
10921 
10922 
10923 /***
10924  * DESCRIPTION:
10925  * Processes double click messages (right mouse button).
10926  *
10927  * PARAMETER(S):
10928  * [I] infoPtr : valid pointer to the listview structure
10929  * [I] wKey : key flag
10930  * [I] x,y : mouse coordinate
10931  *
10932  * RETURN:
10933  * Zero
10934  */
10935 static LRESULT LISTVIEW_RButtonDblClk(const LISTVIEW_INFO *infoPtr, WORD wKey, INT x, INT y)
10936 {
10937     LVHITTESTINFO lvHitTestInfo;
10938 
10939     TRACE("(key=%hu,X=%u,Y=%u)\n", wKey, x, y);
10940 
10941     /* send NM_RELEASEDCAPTURE notification */
10942     if (!notify(infoPtr, NM_RELEASEDCAPTURE)) return 0;
10943 
10944     /* send NM_RDBLCLK notification */
10945     lvHitTestInfo.pt.x = x;
10946     lvHitTestInfo.pt.y = y;
10947     LISTVIEW_HitTest(infoPtr, &lvHitTestInfo, TRUE, FALSE);
10948     notify_click(infoPtr, NM_RDBLCLK, &lvHitTestInfo);
10949 
10950     return 0;
10951 }
10952 
10953 /***
10954  * DESCRIPTION:
10955  * Processes WM_RBUTTONDOWN message and corresponding drag operation.
10956  *
10957  * PARAMETER(S):
10958  * [I] infoPtr : valid pointer to the listview structure
10959  * [I] wKey : key flag
10960  * [I] x, y : mouse coordinate
10961  *
10962  * RETURN:
10963  * Zero
10964  */
10965 static LRESULT LISTVIEW_RButtonDown(LISTVIEW_INFO *infoPtr, WORD wKey, INT x, INT y)
10966 {
10967     LVHITTESTINFO ht;
10968     INT item;
10969 
10970     TRACE("(key=%hu, x=%d, y=%d)\n", wKey, x, y);
10971 
10972     /* send NM_RELEASEDCAPTURE notification */
10973     if (!notify(infoPtr, NM_RELEASEDCAPTURE)) return 0;
10974 
10975     /* determine the index of the selected item */
10976     ht.pt.x = x;
10977     ht.pt.y = y;
10978     item = LISTVIEW_HitTest(infoPtr, &ht, TRUE, TRUE);
10979 
10980     /* make sure the listview control window has the focus */
10981     if (!infoPtr->bFocus) SetFocus(infoPtr->hwndSelf);
10982 
10983     if ((item >= 0) && (item < infoPtr->nItemCount))
10984     {
10985 	LISTVIEW_SetItemFocus(infoPtr, item);
10986 	if (!((wKey & MK_SHIFT) || (wKey & MK_CONTROL)) &&
10987             !LISTVIEW_GetItemState(infoPtr, item, LVIS_SELECTED))
10988 	    LISTVIEW_SetSelection(infoPtr, item);
10989     }
10990     else
10991 	LISTVIEW_DeselectAll(infoPtr);
10992 
10993     if (LISTVIEW_TrackMouse(infoPtr, ht.pt))
10994     {
10995 	if (ht.iItem != -1)
10996 	{
10997             NMLISTVIEW nmlv;
10998 
10999             memset(&nmlv, 0, sizeof(nmlv));
11000             nmlv.iItem = ht.iItem;
11001             nmlv.ptAction = ht.pt;
11002 
11003             notify_listview(infoPtr, LVN_BEGINRDRAG, &nmlv);
11004 	}
11005     }
11006     else
11007     {
11008 	SetFocus(infoPtr->hwndSelf);
11009 
11010         ht.pt.x = x;
11011         ht.pt.y = y;
11012         LISTVIEW_HitTest(infoPtr, &ht, TRUE, FALSE);
11013 
11014 	if (notify_click(infoPtr, NM_RCLICK, &ht))
11015 	{
11016 	    /* Send a WM_CONTEXTMENU message in response to the WM_RBUTTONUP */
11017 	    SendMessageW(infoPtr->hwndSelf, WM_CONTEXTMENU,
11018 		(WPARAM)infoPtr->hwndSelf, (LPARAM)GetMessagePos());
11019 	}
11020     }
11021 
11022     return 0;
11023 }
11024 
11025 /***
11026  * DESCRIPTION:
11027  * Sets the cursor.
11028  *
11029  * PARAMETER(S):
11030  * [I] infoPtr : valid pointer to the listview structure
11031  * [I] hwnd : window handle of window containing the cursor
11032  * [I] nHittest : hit-test code
11033  * [I] wMouseMsg : ideintifier of the mouse message
11034  *
11035  * RETURN:
11036  * TRUE if cursor is set
11037  * FALSE otherwise
11038  */
11039 static BOOL LISTVIEW_SetCursor(const LISTVIEW_INFO *infoPtr, WPARAM wParam, LPARAM lParam)
11040 {
11041     LVHITTESTINFO lvHitTestInfo;
11042 
11043     if (!LISTVIEW_IsHotTracking(infoPtr)) goto forward;
11044 
11045     if (!infoPtr->hHotCursor) goto forward;
11046 
11047     GetCursorPos(&lvHitTestInfo.pt);
11048     if (LISTVIEW_HitTest(infoPtr, &lvHitTestInfo, FALSE, FALSE) < 0) goto forward;
11049 
11050     SetCursor(infoPtr->hHotCursor);
11051 
11052     return TRUE;
11053 
11054 forward:
11055 
11056     return DefWindowProcW(infoPtr->hwndSelf, WM_SETCURSOR, wParam, lParam);
11057 }
11058 
11059 /***
11060  * DESCRIPTION:
11061  * Sets the focus.
11062  *
11063  * PARAMETER(S):
11064  * [I] infoPtr : valid pointer to the listview structure
11065  * [I] hwndLoseFocus : handle of previously focused window
11066  *
11067  * RETURN:
11068  * Zero
11069  */
11070 static LRESULT LISTVIEW_SetFocus(LISTVIEW_INFO *infoPtr, HWND hwndLoseFocus)
11071 {
11072     TRACE("(hwndLoseFocus=%p)\n", hwndLoseFocus);
11073 
11074     /* if we have the focus already, there's nothing to do */
11075     if (infoPtr->bFocus) return 0;
11076 
11077     /* send NM_SETFOCUS notification */
11078     if (!notify(infoPtr, NM_SETFOCUS)) return 0;
11079 
11080     /* set window focus flag */
11081     infoPtr->bFocus = TRUE;
11082 
11083     /* put the focus rect back on */
11084     LISTVIEW_ShowFocusRect(infoPtr, TRUE);
11085 
11086     /* redraw all visible selected items */
11087     LISTVIEW_InvalidateSelectedItems(infoPtr);
11088 
11089     return 0;
11090 }
11091 
11092 /***
11093  * DESCRIPTION:
11094  * Sets the font.
11095  *
11096  * PARAMETER(S):
11097  * [I] infoPtr : valid pointer to the listview structure
11098  * [I] fRedraw : font handle
11099  * [I] fRedraw : redraw flag
11100  *
11101  * RETURN:
11102  * Zero
11103  */
11104 static LRESULT LISTVIEW_SetFont(LISTVIEW_INFO *infoPtr, HFONT hFont, WORD fRedraw)
11105 {
11106     HFONT oldFont = infoPtr->hFont;
11107     INT oldHeight = infoPtr->nItemHeight;
11108 
11109     TRACE("(hfont=%p,redraw=%hu)\n", hFont, fRedraw);
11110 
11111     infoPtr->hFont = hFont ? hFont : infoPtr->hDefaultFont;
11112     if (infoPtr->hFont == oldFont) return 0;
11113 
11114     LISTVIEW_SaveTextMetrics(infoPtr);
11115 
11116     infoPtr->nItemHeight = LISTVIEW_CalculateItemHeight(infoPtr);
11117 
11118     if (infoPtr->uView == LV_VIEW_DETAILS)
11119     {
11120 	SendMessageW(infoPtr->hwndHeader, WM_SETFONT, (WPARAM)hFont, MAKELPARAM(fRedraw, 0));
11121         LISTVIEW_UpdateSize(infoPtr);
11122         LISTVIEW_UpdateScroll(infoPtr);
11123     }
11124     else if (infoPtr->nItemHeight != oldHeight)
11125         LISTVIEW_UpdateScroll(infoPtr);
11126 
11127     if (fRedraw) LISTVIEW_InvalidateList(infoPtr);
11128 
11129     return 0;
11130 }
11131 
11132 /***
11133  * DESCRIPTION:
11134  * Message handling for WM_SETREDRAW.
11135  * For the Listview, it invalidates the entire window (the doc specifies otherwise)
11136  *
11137  * PARAMETER(S):
11138  * [I] infoPtr : valid pointer to the listview structure
11139  * [I] redraw: state of redraw flag
11140  *
11141  * RETURN:
11142  *     Zero.
11143  */
11144 static LRESULT LISTVIEW_SetRedraw(LISTVIEW_INFO *infoPtr, BOOL redraw)
11145 {
11146     TRACE("old=%d, new=%d\n", infoPtr->redraw, redraw);
11147 
11148     if (infoPtr->redraw == !!redraw)
11149         return 0;
11150 
11151     if (!(infoPtr->redraw = !!redraw))
11152         return 0;
11153 
11154     if (is_autoarrange(infoPtr))
11155 	LISTVIEW_Arrange(infoPtr, LVA_DEFAULT);
11156     LISTVIEW_UpdateScroll(infoPtr);
11157 
11158     /* despite what the WM_SETREDRAW docs says, apps expect us
11159      * to invalidate the listview here... stupid! */
11160     LISTVIEW_InvalidateList(infoPtr);
11161 
11162     return 0;
11163 }
11164 
11165 /***
11166  * DESCRIPTION:
11167  * Resizes the listview control. This function processes WM_SIZE
11168  * messages.  At this time, the width and height are not used.
11169  *
11170  * PARAMETER(S):
11171  * [I] infoPtr : valid pointer to the listview structure
11172  * [I] Width : new width
11173  * [I] Height : new height
11174  *
11175  * RETURN:
11176  * Zero
11177  */
11178 static LRESULT LISTVIEW_Size(LISTVIEW_INFO *infoPtr, int Width, int Height)
11179 {
11180     RECT rcOld = infoPtr->rcList;
11181 
11182     TRACE("(width=%d, height=%d)\n", Width, Height);
11183 
11184     LISTVIEW_UpdateSize(infoPtr);
11185     if (EqualRect(&rcOld, &infoPtr->rcList)) return 0;
11186 
11187     /* do not bother with display related stuff if we're not redrawing */
11188     if (!is_redrawing(infoPtr)) return 0;
11189 
11190     if (is_autoarrange(infoPtr))
11191 	LISTVIEW_Arrange(infoPtr, LVA_DEFAULT);
11192 
11193     LISTVIEW_UpdateScroll(infoPtr);
11194 
11195     /* refresh all only for lists whose height changed significantly */
11196     if ((infoPtr->uView == LV_VIEW_LIST) &&
11197 	(rcOld.bottom - rcOld.top) / infoPtr->nItemHeight !=
11198 	(infoPtr->rcList.bottom - infoPtr->rcList.top) / infoPtr->nItemHeight)
11199 	LISTVIEW_InvalidateList(infoPtr);
11200 
11201   return 0;
11202 }
11203 
11204 /***
11205  * DESCRIPTION:
11206  * Sets the size information.
11207  *
11208  * PARAMETER(S):
11209  * [I] infoPtr : valid pointer to the listview structure
11210  *
11211  * RETURN:
11212  *  None
11213  */
11214 static void LISTVIEW_UpdateSize(LISTVIEW_INFO *infoPtr)
11215 {
11216     TRACE("uView=%d, rcList(old)=%s\n", infoPtr->uView, wine_dbgstr_rect(&infoPtr->rcList));
11217 
11218     GetClientRect(infoPtr->hwndSelf, &infoPtr->rcList);
11219 
11220     if (infoPtr->uView == LV_VIEW_LIST)
11221     {
11222 	/* Apparently the "LIST" style is supposed to have the same
11223 	 * number of items in a column even if there is no scroll bar.
11224 	 * Since if a scroll bar already exists then the bottom is already
11225 	 * reduced, only reduce if the scroll bar does not currently exist.
11226 	 * The "2" is there to mimic the native control. I think it may be
11227 	 * related to either padding or edges.  (GLA 7/2002)
11228 	 */
11229 	if (!(GetWindowLongW(infoPtr->hwndSelf, GWL_STYLE) & WS_HSCROLL))
11230 	    infoPtr->rcList.bottom -= GetSystemMetrics(SM_CYHSCROLL);
11231         infoPtr->rcList.bottom = max (infoPtr->rcList.bottom - 2, 0);
11232     }
11233 
11234     /* When ListView control is created invisible, header isn't created right away. */
11235     if (infoPtr->hwndHeader)
11236     {
11237         POINT origin;
11238         WINDOWPOS wp;
11239         HDLAYOUT hl;
11240         RECT rect;
11241 
11242         LISTVIEW_GetOrigin(infoPtr, &origin);
11243 
11244         rect = infoPtr->rcList;
11245         rect.left += origin.x;
11246         rect.top += origin.y;
11247 
11248         hl.prc = &rect;
11249 	hl.pwpos = &wp;
11250 	SendMessageW( infoPtr->hwndHeader, HDM_LAYOUT, 0, (LPARAM)&hl );
11251 	TRACE("  wp.flags=0x%08x, wp=%d,%d (%dx%d)\n", wp.flags, wp.x, wp.y, wp.cx, wp.cy);
11252 
11253 	if (LISTVIEW_IsHeaderEnabled(infoPtr))
11254 	    wp.flags |= SWP_SHOWWINDOW;
11255 	else
11256 	{
11257 	    wp.flags |= SWP_HIDEWINDOW;
11258 	    wp.cy = 0;
11259 	}
11260 
11261 	SetWindowPos(wp.hwnd, wp.hwndInsertAfter, wp.x, wp.y, wp.cx, wp.cy, wp.flags);
11262 	TRACE("  after SWP wp=%d,%d (%dx%d)\n", wp.x, wp.y, wp.cx, wp.cy);
11263 
11264 	infoPtr->rcList.top = max(wp.cy, 0);
11265     }
11266     /* extra padding for grid */
11267     if (infoPtr->uView == LV_VIEW_DETAILS && infoPtr->dwLvExStyle & LVS_EX_GRIDLINES)
11268 	infoPtr->rcList.top += 2;
11269 
11270     TRACE("  rcList=%s\n", wine_dbgstr_rect(&infoPtr->rcList));
11271 }
11272 
11273 /***
11274  * DESCRIPTION:
11275  * Processes WM_STYLECHANGED messages.
11276  *
11277  * PARAMETER(S):
11278  * [I] infoPtr : valid pointer to the listview structure
11279  * [I] wStyleType : window style type (normal or extended)
11280  * [I] lpss : window style information
11281  *
11282  * RETURN:
11283  * Zero
11284  */
11285 static INT LISTVIEW_StyleChanged(LISTVIEW_INFO *infoPtr, WPARAM wStyleType,
11286                                  const STYLESTRUCT *lpss)
11287 {
11288     UINT uNewView, uOldView;
11289     UINT style;
11290 
11291     TRACE("(styletype=%lx, styleOld=0x%08x, styleNew=0x%08x)\n",
11292           wStyleType, lpss->styleOld, lpss->styleNew);
11293 
11294     if (wStyleType != GWL_STYLE || lpss->styleNew == infoPtr->dwStyle) return 0;
11295 
11296     infoPtr->dwStyle = lpss->styleNew;
11297 
11298     if (((lpss->styleOld & WS_HSCROLL) != 0)&&
11299         ((lpss->styleNew & WS_HSCROLL) == 0))
11300        ShowScrollBar(infoPtr->hwndSelf, SB_HORZ, FALSE);
11301 
11302     if (((lpss->styleOld & WS_VSCROLL) != 0)&&
11303         ((lpss->styleNew & WS_VSCROLL) == 0))
11304        ShowScrollBar(infoPtr->hwndSelf, SB_VERT, FALSE);
11305 
11306     uNewView = lpss->styleNew & LVS_TYPEMASK;
11307     uOldView = lpss->styleOld & LVS_TYPEMASK;
11308 
11309     if (uNewView != uOldView)
11310     {
11311     	HIMAGELIST himl;
11312 
11313         /* LVM_SETVIEW doesn't change window style bits within LVS_TYPEMASK,
11314            changing style updates current view only when view bits change. */
11315         map_style_view(infoPtr);
11316         SendMessageW(infoPtr->hwndEdit, WM_KILLFOCUS, 0, 0);
11317     	ShowWindow(infoPtr->hwndHeader, SW_HIDE);
11318 
11319         ShowScrollBar(infoPtr->hwndSelf, SB_BOTH, FALSE);
11320         SetRectEmpty(&infoPtr->rcFocus);
11321 
11322         himl = (uNewView == LVS_ICON ? infoPtr->himlNormal : infoPtr->himlSmall);
11323         set_icon_size(&infoPtr->iconSize, himl, uNewView != LVS_ICON);
11324 
11325         if (uNewView == LVS_REPORT)
11326         {
11327             HDLAYOUT hl;
11328             WINDOWPOS wp;
11329 
11330             LISTVIEW_CreateHeader( infoPtr );
11331 
11332             hl.prc = &infoPtr->rcList;
11333             hl.pwpos = &wp;
11334             SendMessageW( infoPtr->hwndHeader, HDM_LAYOUT, 0, (LPARAM)&hl );
11335             SetWindowPos(infoPtr->hwndHeader, infoPtr->hwndSelf, wp.x, wp.y, wp.cx, wp.cy,
11336                     wp.flags | ((infoPtr->dwStyle & LVS_NOCOLUMNHEADER)
11337                         ? SWP_HIDEWINDOW : SWP_SHOWWINDOW));
11338         }
11339 
11340 	LISTVIEW_UpdateItemSize(infoPtr);
11341     }
11342 
11343     if (uNewView == LVS_REPORT || infoPtr->dwLvExStyle & LVS_EX_HEADERINALLVIEWS)
11344     {
11345         if ((lpss->styleOld ^ lpss->styleNew) & LVS_NOCOLUMNHEADER)
11346         {
11347             if (lpss->styleNew & LVS_NOCOLUMNHEADER)
11348             {
11349                 /* Turn off the header control */
11350                 style = GetWindowLongW(infoPtr->hwndHeader, GWL_STYLE);
11351                 TRACE("Hide header control, was 0x%08x\n", style);
11352                 SetWindowLongW(infoPtr->hwndHeader, GWL_STYLE, style | HDS_HIDDEN);
11353             } else {
11354                 /* Turn on the header control */
11355                 if ((style = GetWindowLongW(infoPtr->hwndHeader, GWL_STYLE)) & HDS_HIDDEN)
11356                 {
11357                     TRACE("Show header control, was 0x%08x\n", style);
11358                     SetWindowLongW(infoPtr->hwndHeader, GWL_STYLE, (style & ~HDS_HIDDEN) | WS_VISIBLE);
11359                 }
11360             }
11361         }
11362     }
11363 
11364     if ( (uNewView == LVS_ICON || uNewView == LVS_SMALLICON) &&
11365 	 (uNewView != uOldView || ((lpss->styleNew ^ lpss->styleOld) & LVS_ALIGNMASK)) )
11366 	 LISTVIEW_Arrange(infoPtr, LVA_DEFAULT);
11367 
11368     /* update the size of the client area */
11369     LISTVIEW_UpdateSize(infoPtr);
11370 
11371     /* add scrollbars if needed */
11372     LISTVIEW_UpdateScroll(infoPtr);
11373 
11374     /* invalidate client area + erase background */
11375     LISTVIEW_InvalidateList(infoPtr);
11376 
11377     return 0;
11378 }
11379 
11380 /***
11381  * DESCRIPTION:
11382  * Processes WM_STYLECHANGING messages.
11383  *
11384  * PARAMETER(S):
11385  * [I] wStyleType : window style type (normal or extended)
11386  * [I0] lpss : window style information
11387  *
11388  * RETURN:
11389  * Zero
11390  */
11391 static INT LISTVIEW_StyleChanging(WPARAM wStyleType,
11392                                   STYLESTRUCT *lpss)
11393 {
11394     TRACE("(styletype=%lx, styleOld=0x%08x, styleNew=0x%08x)\n",
11395           wStyleType, lpss->styleOld, lpss->styleNew);
11396 
11397     /* don't forward LVS_OWNERDATA only if not already set to */
11398     if ((lpss->styleNew ^ lpss->styleOld) & LVS_OWNERDATA)
11399     {
11400         if (lpss->styleOld & LVS_OWNERDATA)
11401             lpss->styleNew |= LVS_OWNERDATA;
11402         else
11403             lpss->styleNew &= ~LVS_OWNERDATA;
11404     }
11405 
11406     return 0;
11407 }
11408 
11409 /***
11410  * DESCRIPTION:
11411  * Processes WM_SHOWWINDOW messages.
11412  *
11413  * PARAMETER(S):
11414  * [I] infoPtr : valid pointer to the listview structure
11415  * [I] bShown  : window is being shown (FALSE when hidden)
11416  * [I] iStatus : window show status
11417  *
11418  * RETURN:
11419  * Zero
11420  */
11421 static LRESULT LISTVIEW_ShowWindow(LISTVIEW_INFO *infoPtr, WPARAM bShown, LPARAM iStatus)
11422 {
11423   /* header delayed creation */
11424   if ((infoPtr->uView == LV_VIEW_DETAILS) && bShown)
11425   {
11426     LISTVIEW_CreateHeader(infoPtr);
11427 
11428     if (!(LVS_NOCOLUMNHEADER & infoPtr->dwStyle))
11429       ShowWindow(infoPtr->hwndHeader, SW_SHOWNORMAL);
11430   }
11431 
11432   return DefWindowProcW(infoPtr->hwndSelf, WM_SHOWWINDOW, bShown, iStatus);
11433 }
11434 
11435 /***
11436  * DESCRIPTION:
11437  * Processes CCM_GETVERSION messages.
11438  *
11439  * PARAMETER(S):
11440  * [I] infoPtr : valid pointer to the listview structure
11441  *
11442  * RETURN:
11443  * Current version
11444  */
11445 static inline LRESULT LISTVIEW_GetVersion(const LISTVIEW_INFO *infoPtr)
11446 {
11447   return infoPtr->iVersion;
11448 }
11449 
11450 /***
11451  * DESCRIPTION:
11452  * Processes CCM_SETVERSION messages.
11453  *
11454  * PARAMETER(S):
11455  * [I] infoPtr  : valid pointer to the listview structure
11456  * [I] iVersion : version to be set
11457  *
11458  * RETURN:
11459  * -1 when requested version is greater than DLL version;
11460  * previous version otherwise
11461  */
11462 static LRESULT LISTVIEW_SetVersion(LISTVIEW_INFO *infoPtr, DWORD iVersion)
11463 {
11464   INT iOldVersion = infoPtr->iVersion;
11465 
11466   if (iVersion > COMCTL32_VERSION)
11467     return -1;
11468 
11469   infoPtr->iVersion = iVersion;
11470 
11471   TRACE("new version %d\n", iVersion);
11472 
11473   return iOldVersion;
11474 }
11475 
11476 /***
11477  * DESCRIPTION:
11478  * Window procedure of the listview control.
11479  *
11480  */
11481 static LRESULT WINAPI
11482 LISTVIEW_WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
11483 {
11484   LISTVIEW_INFO *infoPtr = (LISTVIEW_INFO *)GetWindowLongPtrW(hwnd, 0);
11485 
11486   TRACE("(hwnd=%p uMsg=%x wParam=%lx lParam=%lx)\n", hwnd, uMsg, wParam, lParam);
11487 
11488   if (!infoPtr && (uMsg != WM_NCCREATE))
11489     return DefWindowProcW(hwnd, uMsg, wParam, lParam);
11490 
11491   switch (uMsg)
11492   {
11493   case LVM_APPROXIMATEVIEWRECT:
11494     return LISTVIEW_ApproximateViewRect(infoPtr, (INT)wParam,
11495                                         LOWORD(lParam), HIWORD(lParam));
11496   case LVM_ARRANGE:
11497     return LISTVIEW_Arrange(infoPtr, (INT)wParam);
11498 
11499   case LVM_CANCELEDITLABEL:
11500     return LISTVIEW_CancelEditLabel(infoPtr);
11501 
11502   case LVM_CREATEDRAGIMAGE:
11503     return (LRESULT)LISTVIEW_CreateDragImage(infoPtr, (INT)wParam, (LPPOINT)lParam);
11504 
11505   case LVM_DELETEALLITEMS:
11506     return LISTVIEW_DeleteAllItems(infoPtr, FALSE);
11507 
11508   case LVM_DELETECOLUMN:
11509     return LISTVIEW_DeleteColumn(infoPtr, (INT)wParam);
11510 
11511   case LVM_DELETEITEM:
11512     return LISTVIEW_DeleteItem(infoPtr, (INT)wParam);
11513 
11514   case LVM_EDITLABELA:
11515   case LVM_EDITLABELW:
11516     return (LRESULT)LISTVIEW_EditLabelT(infoPtr, (INT)wParam,
11517                                         uMsg == LVM_EDITLABELW);
11518   /* case LVM_ENABLEGROUPVIEW: */
11519 
11520   case LVM_ENSUREVISIBLE:
11521     return LISTVIEW_EnsureVisible(infoPtr, (INT)wParam, (BOOL)lParam);
11522 
11523   case LVM_FINDITEMW:
11524     return LISTVIEW_FindItemW(infoPtr, (INT)wParam, (LPLVFINDINFOW)lParam);
11525 
11526   case LVM_FINDITEMA:
11527     return LISTVIEW_FindItemA(infoPtr, (INT)wParam, (LPLVFINDINFOA)lParam);
11528 
11529   case LVM_GETBKCOLOR:
11530     return infoPtr->clrBk;
11531 
11532   /* case LVM_GETBKIMAGE: */
11533 
11534   case LVM_GETCALLBACKMASK:
11535     return infoPtr->uCallbackMask;
11536 
11537   case LVM_GETCOLUMNA:
11538   case LVM_GETCOLUMNW:
11539     return LISTVIEW_GetColumnT(infoPtr, (INT)wParam, (LPLVCOLUMNW)lParam,
11540                                uMsg == LVM_GETCOLUMNW);
11541 
11542   case LVM_GETCOLUMNORDERARRAY:
11543     return LISTVIEW_GetColumnOrderArray(infoPtr, (INT)wParam, (LPINT)lParam);
11544 
11545   case LVM_GETCOLUMNWIDTH:
11546     return LISTVIEW_GetColumnWidth(infoPtr, (INT)wParam);
11547 
11548   case LVM_GETCOUNTPERPAGE:
11549     return LISTVIEW_GetCountPerPage(infoPtr);
11550 
11551   case LVM_GETEDITCONTROL:
11552     return (LRESULT)infoPtr->hwndEdit;
11553 
11554   case LVM_GETEXTENDEDLISTVIEWSTYLE:
11555     return infoPtr->dwLvExStyle;
11556 
11557   /* case LVM_GETGROUPINFO: */
11558 
11559   /* case LVM_GETGROUPMETRICS: */
11560 
11561   case LVM_GETHEADER:
11562     return (LRESULT)infoPtr->hwndHeader;
11563 
11564   case LVM_GETHOTCURSOR:
11565     return (LRESULT)infoPtr->hHotCursor;
11566 
11567   case LVM_GETHOTITEM:
11568     return infoPtr->nHotItem;
11569 
11570   case LVM_GETHOVERTIME:
11571     return infoPtr->dwHoverTime;
11572 
11573   case LVM_GETIMAGELIST:
11574     return (LRESULT)LISTVIEW_GetImageList(infoPtr, (INT)wParam);
11575 
11576   /* case LVM_GETINSERTMARK: */
11577 
11578   /* case LVM_GETINSERTMARKCOLOR: */
11579 
11580   /* case LVM_GETINSERTMARKRECT: */
11581 
11582   case LVM_GETISEARCHSTRINGA:
11583   case LVM_GETISEARCHSTRINGW:
11584     FIXME("LVM_GETISEARCHSTRING: unimplemented\n");
11585     return FALSE;
11586 
11587   case LVM_GETITEMA:
11588   case LVM_GETITEMW:
11589     return LISTVIEW_GetItemExtT(infoPtr, (LPLVITEMW)lParam, uMsg == LVM_GETITEMW);
11590 
11591   case LVM_GETITEMCOUNT:
11592     return infoPtr->nItemCount;
11593 
11594   case LVM_GETITEMPOSITION:
11595     return LISTVIEW_GetItemPosition(infoPtr, (INT)wParam, (LPPOINT)lParam);
11596 
11597   case LVM_GETITEMRECT:
11598     return LISTVIEW_GetItemRect(infoPtr, (INT)wParam, (LPRECT)lParam);
11599 
11600   case LVM_GETITEMSPACING:
11601     return LISTVIEW_GetItemSpacing(infoPtr, (BOOL)wParam);
11602 
11603   case LVM_GETITEMSTATE:
11604     return LISTVIEW_GetItemState(infoPtr, (INT)wParam, (UINT)lParam);
11605 
11606   case LVM_GETITEMTEXTA:
11607   case LVM_GETITEMTEXTW:
11608     return LISTVIEW_GetItemTextT(infoPtr, (INT)wParam, (LPLVITEMW)lParam,
11609                                  uMsg == LVM_GETITEMTEXTW);
11610 
11611   case LVM_GETNEXTITEM:
11612     return LISTVIEW_GetNextItem(infoPtr, (INT)wParam, LOWORD(lParam));
11613 
11614   case LVM_GETNUMBEROFWORKAREAS:
11615     FIXME("LVM_GETNUMBEROFWORKAREAS: unimplemented\n");
11616     return 1;
11617 
11618   case LVM_GETORIGIN:
11619     if (!lParam) return FALSE;
11620     if (infoPtr->uView == LV_VIEW_DETAILS ||
11621         infoPtr->uView == LV_VIEW_LIST) return FALSE;
11622     LISTVIEW_GetOrigin(infoPtr, (LPPOINT)lParam);
11623     return TRUE;
11624 
11625   /* case LVM_GETOUTLINECOLOR: */
11626 
11627   /* case LVM_GETSELECTEDCOLUMN: */
11628 
11629   case LVM_GETSELECTEDCOUNT:
11630     return LISTVIEW_GetSelectedCount(infoPtr);
11631 
11632   case LVM_GETSELECTIONMARK:
11633     return infoPtr->nSelectionMark;
11634 
11635   case LVM_GETSTRINGWIDTHA:
11636   case LVM_GETSTRINGWIDTHW:
11637     return LISTVIEW_GetStringWidthT(infoPtr, (LPCWSTR)lParam,
11638                                     uMsg == LVM_GETSTRINGWIDTHW);
11639 
11640   case LVM_GETSUBITEMRECT:
11641     return LISTVIEW_GetSubItemRect(infoPtr, (UINT)wParam, (LPRECT)lParam);
11642 
11643   case LVM_GETTEXTBKCOLOR:
11644     return infoPtr->clrTextBk;
11645 
11646   case LVM_GETTEXTCOLOR:
11647     return infoPtr->clrText;
11648 
11649   /* case LVM_GETTILEINFO: */
11650 
11651   /* case LVM_GETTILEVIEWINFO: */
11652 
11653   case LVM_GETTOOLTIPS:
11654     if( !infoPtr->hwndToolTip )
11655         infoPtr->hwndToolTip = COMCTL32_CreateToolTip( hwnd );
11656     return (LRESULT)infoPtr->hwndToolTip;
11657 
11658   case LVM_GETTOPINDEX:
11659     return LISTVIEW_GetTopIndex(infoPtr);
11660 
11661   case LVM_GETUNICODEFORMAT:
11662     return (infoPtr->notifyFormat == NFR_UNICODE);
11663 
11664   case LVM_GETVIEW:
11665     return infoPtr->uView;
11666 
11667   case LVM_GETVIEWRECT:
11668     return LISTVIEW_GetViewRect(infoPtr, (LPRECT)lParam);
11669 
11670   case LVM_GETWORKAREAS:
11671     FIXME("LVM_GETWORKAREAS: unimplemented\n");
11672     return FALSE;
11673 
11674   /* case LVM_HASGROUP: */
11675 
11676   case LVM_HITTEST:
11677     return LISTVIEW_HitTest(infoPtr, (LPLVHITTESTINFO)lParam, FALSE, TRUE);
11678 
11679   case LVM_INSERTCOLUMNA:
11680   case LVM_INSERTCOLUMNW:
11681     return LISTVIEW_InsertColumnT(infoPtr, (INT)wParam, (LPLVCOLUMNW)lParam,
11682                                   uMsg == LVM_INSERTCOLUMNW);
11683 
11684   /* case LVM_INSERTGROUP: */
11685 
11686   /* case LVM_INSERTGROUPSORTED: */
11687 
11688   case LVM_INSERTITEMA:
11689   case LVM_INSERTITEMW:
11690     return LISTVIEW_InsertItemT(infoPtr, (LPLVITEMW)lParam, uMsg == LVM_INSERTITEMW);
11691 
11692   /* case LVM_INSERTMARKHITTEST: */
11693 
11694   /* case LVM_ISGROUPVIEWENABLED: */
11695 
11696   case LVM_ISITEMVISIBLE:
11697     return LISTVIEW_IsItemVisible(infoPtr, (INT)wParam);
11698 
11699   case LVM_MAPIDTOINDEX:
11700     return LISTVIEW_MapIdToIndex(infoPtr, (UINT)wParam);
11701 
11702   case LVM_MAPINDEXTOID:
11703     return LISTVIEW_MapIndexToId(infoPtr, (INT)wParam);
11704 
11705   /* case LVM_MOVEGROUP: */
11706 
11707   /* case LVM_MOVEITEMTOGROUP: */
11708 
11709   case LVM_REDRAWITEMS:
11710     return LISTVIEW_RedrawItems(infoPtr, (INT)wParam, (INT)lParam);
11711 
11712   /* case LVM_REMOVEALLGROUPS: */
11713 
11714   /* case LVM_REMOVEGROUP: */
11715 
11716   case LVM_SCROLL:
11717     return LISTVIEW_Scroll(infoPtr, (INT)wParam, (INT)lParam);
11718 
11719   case LVM_SETBKCOLOR:
11720     return LISTVIEW_SetBkColor(infoPtr, (COLORREF)lParam);
11721 
11722   /* case LVM_SETBKIMAGE: */
11723 
11724   case LVM_SETCALLBACKMASK:
11725     infoPtr->uCallbackMask = (UINT)wParam;
11726     return TRUE;
11727 
11728   case LVM_SETCOLUMNA:
11729   case LVM_SETCOLUMNW:
11730     return LISTVIEW_SetColumnT(infoPtr, (INT)wParam, (LPLVCOLUMNW)lParam,
11731                                uMsg == LVM_SETCOLUMNW);
11732 
11733   case LVM_SETCOLUMNORDERARRAY:
11734     return LISTVIEW_SetColumnOrderArray(infoPtr, (INT)wParam, (LPINT)lParam);
11735 
11736   case LVM_SETCOLUMNWIDTH:
11737     return LISTVIEW_SetColumnWidth(infoPtr, (INT)wParam, (short)LOWORD(lParam));
11738 
11739   case LVM_SETEXTENDEDLISTVIEWSTYLE:
11740     return LISTVIEW_SetExtendedListViewStyle(infoPtr, (DWORD)wParam, (DWORD)lParam);
11741 
11742   /* case LVM_SETGROUPINFO: */
11743 
11744   /* case LVM_SETGROUPMETRICS: */
11745 
11746   case LVM_SETHOTCURSOR:
11747     return (LRESULT)LISTVIEW_SetHotCursor(infoPtr, (HCURSOR)lParam);
11748 
11749   case LVM_SETHOTITEM:
11750     return LISTVIEW_SetHotItem(infoPtr, (INT)wParam);
11751 
11752   case LVM_SETHOVERTIME:
11753     return LISTVIEW_SetHoverTime(infoPtr, (DWORD)lParam);
11754 
11755   case LVM_SETICONSPACING:
11756     if(lParam == -1)
11757         return LISTVIEW_SetIconSpacing(infoPtr, -1, -1);
11758     return LISTVIEW_SetIconSpacing(infoPtr, LOWORD(lParam), HIWORD(lParam));
11759 
11760   case LVM_SETIMAGELIST:
11761     return (LRESULT)LISTVIEW_SetImageList(infoPtr, (INT)wParam, (HIMAGELIST)lParam);
11762 
11763   /* case LVM_SETINFOTIP: */
11764 
11765   /* case LVM_SETINSERTMARK: */
11766 
11767   /* case LVM_SETINSERTMARKCOLOR: */
11768 
11769   case LVM_SETITEMA:
11770   case LVM_SETITEMW:
11771     {
11772 	if (infoPtr->dwStyle & LVS_OWNERDATA) return FALSE;
11773 	return LISTVIEW_SetItemT(infoPtr, (LPLVITEMW)lParam, (uMsg == LVM_SETITEMW));
11774     }
11775 
11776   case LVM_SETITEMCOUNT:
11777     return LISTVIEW_SetItemCount(infoPtr, (INT)wParam, (DWORD)lParam);
11778 
11779   case LVM_SETITEMPOSITION:
11780     {
11781 	POINT pt;
11782         pt.x = (short)LOWORD(lParam);
11783         pt.y = (short)HIWORD(lParam);
11784         return LISTVIEW_SetItemPosition(infoPtr, (INT)wParam, &pt);
11785     }
11786 
11787   case LVM_SETITEMPOSITION32:
11788     return LISTVIEW_SetItemPosition(infoPtr, (INT)wParam, (POINT*)lParam);
11789 
11790   case LVM_SETITEMSTATE:
11791     return LISTVIEW_SetItemState(infoPtr, (INT)wParam, (LPLVITEMW)lParam);
11792 
11793   case LVM_SETITEMTEXTA:
11794   case LVM_SETITEMTEXTW:
11795     return LISTVIEW_SetItemTextT(infoPtr, (INT)wParam, (LPLVITEMW)lParam,
11796                                  uMsg == LVM_SETITEMTEXTW);
11797 
11798   /* case LVM_SETOUTLINECOLOR: */
11799 
11800   /* case LVM_SETSELECTEDCOLUMN: */
11801 
11802   case LVM_SETSELECTIONMARK:
11803     return LISTVIEW_SetSelectionMark(infoPtr, (INT)lParam);
11804 
11805   case LVM_SETTEXTBKCOLOR:
11806     return LISTVIEW_SetTextBkColor(infoPtr, (COLORREF)lParam);
11807 
11808   case LVM_SETTEXTCOLOR:
11809     return LISTVIEW_SetTextColor(infoPtr, (COLORREF)lParam);
11810 
11811   /* case LVM_SETTILEINFO: */
11812 
11813   /* case LVM_SETTILEVIEWINFO: */
11814 
11815   /* case LVM_SETTILEWIDTH: */
11816 
11817   case LVM_SETTOOLTIPS:
11818     return (LRESULT)LISTVIEW_SetToolTips(infoPtr, (HWND)lParam);
11819 
11820   case LVM_SETUNICODEFORMAT:
11821     return LISTVIEW_SetUnicodeFormat(infoPtr, wParam);
11822 
11823   case LVM_SETVIEW:
11824     return LISTVIEW_SetView(infoPtr, wParam);
11825 
11826   /* case LVM_SETWORKAREAS: */
11827 
11828   /* case LVM_SORTGROUPS: */
11829 
11830   case LVM_SORTITEMS:
11831   case LVM_SORTITEMSEX:
11832     return LISTVIEW_SortItems(infoPtr, (PFNLVCOMPARE)lParam, wParam,
11833                               uMsg == LVM_SORTITEMSEX);
11834   case LVM_SUBITEMHITTEST:
11835     return LISTVIEW_HitTest(infoPtr, (LPLVHITTESTINFO)lParam, TRUE, FALSE);
11836 
11837   case LVM_UPDATE:
11838     return LISTVIEW_Update(infoPtr, (INT)wParam);
11839 
11840   case CCM_GETVERSION:
11841     return LISTVIEW_GetVersion(infoPtr);
11842 
11843   case CCM_SETVERSION:
11844     return LISTVIEW_SetVersion(infoPtr, wParam);
11845 
11846   case WM_CHAR:
11847     return LISTVIEW_ProcessLetterKeys( infoPtr, wParam, lParam );
11848 
11849   case WM_COMMAND:
11850     return LISTVIEW_Command(infoPtr, wParam, lParam);
11851 
11852   case WM_NCCREATE:
11853     return LISTVIEW_NCCreate(hwnd, wParam, (LPCREATESTRUCTW)lParam);
11854 
11855   case WM_CREATE:
11856     return LISTVIEW_Create(hwnd, (LPCREATESTRUCTW)lParam);
11857 
11858   case WM_DESTROY:
11859     return LISTVIEW_Destroy(infoPtr);
11860 
11861   case WM_ENABLE:
11862     return LISTVIEW_Enable(infoPtr);
11863 
11864   case WM_ERASEBKGND:
11865     return LISTVIEW_EraseBkgnd(infoPtr, (HDC)wParam);
11866 
11867   case WM_GETDLGCODE:
11868     return DLGC_WANTCHARS | DLGC_WANTARROWS;
11869 
11870   case WM_GETFONT:
11871     return (LRESULT)infoPtr->hFont;
11872 
11873   case WM_HSCROLL:
11874     return LISTVIEW_HScroll(infoPtr, (INT)LOWORD(wParam), 0);
11875 
11876   case WM_KEYDOWN:
11877     return LISTVIEW_KeyDown(infoPtr, (INT)wParam, (LONG)lParam);
11878 
11879   case WM_KILLFOCUS:
11880     return LISTVIEW_KillFocus(infoPtr);
11881 
11882   case WM_LBUTTONDBLCLK:
11883     return LISTVIEW_LButtonDblClk(infoPtr, (WORD)wParam, (SHORT)LOWORD(lParam), (SHORT)HIWORD(lParam));
11884 
11885   case WM_LBUTTONDOWN:
11886     return LISTVIEW_LButtonDown(infoPtr, (WORD)wParam, (SHORT)LOWORD(lParam), (SHORT)HIWORD(lParam));
11887 
11888   case WM_LBUTTONUP:
11889     return LISTVIEW_LButtonUp(infoPtr, (WORD)wParam, (SHORT)LOWORD(lParam), (SHORT)HIWORD(lParam));
11890 
11891   case WM_MOUSEMOVE:
11892     return LISTVIEW_MouseMove (infoPtr, (WORD)wParam, (SHORT)LOWORD(lParam), (SHORT)HIWORD(lParam));
11893 
11894   case WM_MOUSEHOVER:
11895     return LISTVIEW_MouseHover(infoPtr, (SHORT)LOWORD(lParam), (SHORT)HIWORD(lParam));
11896 
11897   case WM_NCDESTROY:
11898     return LISTVIEW_NCDestroy(infoPtr);
11899 
11900   case WM_NCPAINT:
11901     return LISTVIEW_NCPaint(infoPtr, (HRGN)wParam);
11902 
11903   case WM_NOTIFY:
11904     return LISTVIEW_Notify(infoPtr, (LPNMHDR)lParam);
11905 
11906   case WM_NOTIFYFORMAT:
11907     return LISTVIEW_NotifyFormat(infoPtr, (HWND)wParam, (INT)lParam);
11908 
11909   case WM_PRINTCLIENT:
11910     return LISTVIEW_PrintClient(infoPtr, (HDC)wParam, (DWORD)lParam);
11911 
11912   case WM_PAINT:
11913     return LISTVIEW_WMPaint(infoPtr, (HDC)wParam);
11914 
11915   case WM_RBUTTONDBLCLK:
11916     return LISTVIEW_RButtonDblClk(infoPtr, (WORD)wParam, (SHORT)LOWORD(lParam), (SHORT)HIWORD(lParam));
11917 
11918   case WM_RBUTTONDOWN:
11919     return LISTVIEW_RButtonDown(infoPtr, (WORD)wParam, (SHORT)LOWORD(lParam), (SHORT)HIWORD(lParam));
11920 
11921   case WM_SETCURSOR:
11922     return LISTVIEW_SetCursor(infoPtr, wParam, lParam);
11923 
11924   case WM_SETFOCUS:
11925     return LISTVIEW_SetFocus(infoPtr, (HWND)wParam);
11926 
11927   case WM_SETFONT:
11928     return LISTVIEW_SetFont(infoPtr, (HFONT)wParam, (WORD)lParam);
11929 
11930   case WM_SETREDRAW:
11931     return LISTVIEW_SetRedraw(infoPtr, (BOOL)wParam);
11932 
11933   case WM_SHOWWINDOW:
11934     return LISTVIEW_ShowWindow(infoPtr, wParam, lParam);
11935 
11936   case WM_STYLECHANGED:
11937     return LISTVIEW_StyleChanged(infoPtr, wParam, (LPSTYLESTRUCT)lParam);
11938 
11939   case WM_STYLECHANGING:
11940     return LISTVIEW_StyleChanging(wParam, (LPSTYLESTRUCT)lParam);
11941 
11942   case WM_SYSCOLORCHANGE:
11943     COMCTL32_RefreshSysColors();
11944 #ifdef __REACTOS__
11945     if (infoPtr->bDefaultBkColor)
11946     {
11947         LISTVIEW_SetBkColor(infoPtr, comctl32_color.clrWindow);
11948         infoPtr->bDefaultBkColor = TRUE;
11949         LISTVIEW_InvalidateList(infoPtr);
11950     }
11951 #endif
11952     return 0;
11953 
11954 /*	case WM_TIMER: */
11955   case WM_THEMECHANGED:
11956     return LISTVIEW_ThemeChanged(infoPtr);
11957 
11958   case WM_VSCROLL:
11959     return LISTVIEW_VScroll(infoPtr, (INT)LOWORD(wParam), 0);
11960 
11961   case WM_MOUSEWHEEL:
11962       if (wParam & (MK_SHIFT | MK_CONTROL))
11963           return DefWindowProcW(hwnd, uMsg, wParam, lParam);
11964       return LISTVIEW_MouseWheel(infoPtr, (short int)HIWORD(wParam));
11965 
11966   case WM_WINDOWPOSCHANGED:
11967       if (!(((WINDOWPOS *)lParam)->flags & SWP_NOSIZE))
11968       {
11969           SetWindowPos(infoPtr->hwndSelf, 0, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOACTIVATE |
11970                        SWP_NOZORDER | SWP_NOMOVE | SWP_NOSIZE);
11971 
11972           if ((infoPtr->dwStyle & LVS_OWNERDRAWFIXED) && (infoPtr->uView == LV_VIEW_DETAILS))
11973           {
11974               if (notify_measureitem(infoPtr)) LISTVIEW_InvalidateList(infoPtr);
11975           }
11976           LISTVIEW_Size(infoPtr, ((WINDOWPOS *)lParam)->cx, ((WINDOWPOS *)lParam)->cy);
11977       }
11978       return DefWindowProcW(hwnd, uMsg, wParam, lParam);
11979 
11980 /*	case WM_WININICHANGE: */
11981 
11982   default:
11983     if ((uMsg >= WM_USER) && (uMsg < WM_APP) && !COMCTL32_IsReflectedMessage(uMsg))
11984       ERR("unknown msg %04x wp=%08lx lp=%08lx\n", uMsg, wParam, lParam);
11985 
11986     return DefWindowProcW(hwnd, uMsg, wParam, lParam);
11987   }
11988 
11989 }
11990 
11991 /***
11992  * DESCRIPTION:
11993  * Registers the window class.
11994  *
11995  * PARAMETER(S):
11996  * None
11997  *
11998  * RETURN:
11999  * None
12000  */
12001 void LISTVIEW_Register(void)
12002 {
12003     WNDCLASSW wndClass;
12004 
12005     ZeroMemory(&wndClass, sizeof(WNDCLASSW));
12006     wndClass.style = CS_GLOBALCLASS | CS_DBLCLKS;
12007     wndClass.lpfnWndProc = LISTVIEW_WindowProc;
12008     wndClass.cbClsExtra = 0;
12009     wndClass.cbWndExtra = sizeof(LISTVIEW_INFO *);
12010     wndClass.hCursor = LoadCursorW(0, (LPWSTR)IDC_ARROW);
12011     wndClass.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
12012     wndClass.lpszClassName = WC_LISTVIEWW;
12013     RegisterClassW(&wndClass);
12014 }
12015 
12016 /***
12017  * DESCRIPTION:
12018  * Unregisters the window class.
12019  *
12020  * PARAMETER(S):
12021  * None
12022  *
12023  * RETURN:
12024  * None
12025  */
12026 void LISTVIEW_Unregister(void)
12027 {
12028     UnregisterClassW(WC_LISTVIEWW, NULL);
12029 }
12030 
12031 /***
12032  * DESCRIPTION:
12033  * Handle any WM_COMMAND messages
12034  *
12035  * PARAMETER(S):
12036  * [I] infoPtr : valid pointer to the listview structure
12037  * [I] wParam : the first message parameter
12038  * [I] lParam : the second message parameter
12039  *
12040  * RETURN:
12041  *   Zero.
12042  */
12043 static LRESULT LISTVIEW_Command(LISTVIEW_INFO *infoPtr, WPARAM wParam, LPARAM lParam)
12044 {
12045 
12046     TRACE("(%p %x %x %lx)\n", infoPtr, HIWORD(wParam), LOWORD(wParam), lParam);
12047 
12048     if (!infoPtr->hwndEdit) return 0;
12049 
12050     switch (HIWORD(wParam))
12051     {
12052 	case EN_UPDATE:
12053 	{
12054 	    /*
12055 	     * Adjust the edit window size
12056 	     */
12057 	    WCHAR buffer[1024];
12058 	    HDC           hdc = GetDC(infoPtr->hwndEdit);
12059             HFONT         hFont, hOldFont = 0;
12060 	    RECT	  rect;
12061 	    SIZE	  sz;
12062 
12063 	    if (!infoPtr->hwndEdit || !hdc) return 0;
12064 	    GetWindowTextW(infoPtr->hwndEdit, buffer, ARRAY_SIZE(buffer));
12065 	    GetWindowRect(infoPtr->hwndEdit, &rect);
12066 
12067             /* Select font to get the right dimension of the string */
12068             hFont = (HFONT)SendMessageW(infoPtr->hwndEdit, WM_GETFONT, 0, 0);
12069             if (hFont)
12070             {
12071                 hOldFont = SelectObject(hdc, hFont);
12072             }
12073 
12074 	    if (GetTextExtentPoint32W(hdc, buffer, lstrlenW(buffer), &sz))
12075 	    {
12076                 TEXTMETRICW textMetric;
12077 
12078                 /* Add Extra spacing for the next character */
12079                 GetTextMetricsW(hdc, &textMetric);
12080                 sz.cx += (textMetric.tmMaxCharWidth * 2);
12081 
12082 		SetWindowPos(infoPtr->hwndEdit, NULL, 0, 0, sz.cx,
12083 		    rect.bottom - rect.top, SWP_DRAWFRAME | SWP_NOMOVE | SWP_NOZORDER);
12084 	    }
12085             if (hFont)
12086                 SelectObject(hdc, hOldFont);
12087 
12088 	    ReleaseDC(infoPtr->hwndEdit, hdc);
12089 
12090 	    break;
12091 	}
12092 	case EN_KILLFOCUS:
12093 	{
12094             if (infoPtr->notify_mask & NOTIFY_MASK_END_LABEL_EDIT)
12095                 LISTVIEW_CancelEditLabel(infoPtr);
12096             break;
12097 	}
12098 
12099 	default:
12100 	  return SendMessageW (infoPtr->hwndNotify, WM_COMMAND, wParam, lParam);
12101     }
12102 
12103     return 0;
12104 }
12105