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