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