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