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