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