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