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