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