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