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