~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~ [ freetext search ] ~ [ file search ] ~

Wine Cross Reference
wine/dlls/comctl32/listview.c

Version: ~ [ wine-1.1.33 ] ~ [ wine-1.1.32 ] ~ [ wine-1.1.31 ] ~ [ wine-1.1.30 ] ~ [ wine-1.1.29 ] ~ [ wine-1.1.28 ] ~ [ wine-1.1.27 ] ~ [ wine-1.1.26 ] ~ [ wine-1.1.25 ] ~ [ wine-1.1.24 ] ~ [ wine-1.1.23 ] ~ [ wine-1.1.22 ] ~ [ wine-1.1.21 ] ~ [ wine-1.1.20 ] ~ [ wine-1.1.19 ] ~ [ wine-1.1.18 ] ~ [ wine-1.1.17 ] ~ [ wine-1.1.16 ] ~ [ wine-1.1.15 ] ~ [ wine-1.1.14 ] ~ [ wine-1.1.13 ] ~ [ wine-1.1.12 ] ~ [ wine-1.1.11 ] ~ [ wine-1.1.10 ] ~ [ wine-1.1.9 ] ~ [ wine-1.1.8 ] ~ [ wine-1.1.7 ] ~ [ wine-1.0.1 ] ~ [ wine-1.1.6 ] ~ [ wine-1.1.5 ] ~ [ wine-1.1.4 ] ~ [ wine-1.1.3 ] ~ [ wine-1.1.2 ] ~ [ wine-1.1.1 ] ~ [ wine-1.1.0 ] ~ [ wine-1.0 ] ~

  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  *
 10  * This library is free software; you can redistribute it and/or
 11  * modify it under the terms of the GNU Lesser General Public
 12  * License as published by the Free Software Foundation; either
 13  * version 2.1 of the License, or (at your option) any later version.
 14  *
 15  * This library is distributed in the hope that it will be useful,
 16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
 17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 18  * Lesser General Public License for more details.
 19  *
 20  * You should have received a copy of the GNU Lesser General Public
 21  * License along with this library; if not, write to the Free Software
 22  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
 23  *
 24  * NOTES
 25  *
 26  * This code was audited for completeness against the documented features
 27  * of Comctl32.dll version 6.0 on May. 20, 2005, by James Hawkins.
 28  * 
 29  * Unless otherwise noted, we believe this code to be complete, as per
 30  * the specification mentioned above.
 31  * If you discover missing features, or bugs, please note them below.
 32  * 
 33  * TODO:
 34  *
 35  * Default Message Processing
 36  *   -- EN_KILLFOCUS should be handled in WM_COMMAND
 37  *   -- WM_CREATE: create the icon and small icon image lists at this point only if
 38  *      the LVS_SHAREIMAGELISTS style is not specified.
 39  *   -- WM_ERASEBKGND: forward this message to the parent window if the bkgnd
 40  *      color is CLR_NONE.
 41  *   -- WM_WINDOWPOSCHANGED: arrange the list items if the current view is icon
 42  *      or small icon and the LVS_AUTOARRANGE style is specified.
 43  *   -- WM_TIMER
 44  *   -- WM_WININICHANGE
 45  *
 46  * Features
 47  *   -- Hot item handling, mouse hovering
 48  *   -- Workareas support
 49  *   -- Tilemode support
 50  *   -- Groups support
 51  *
 52  * Bugs
 53  *   -- Expand large item in ICON mode when the cursor is flying over the icon or text.
 54  *   -- Support CustomDraw options for _WIN32_IE >= 0x560 (see NMLVCUSTOMDRAW docs).
 55  *   -- LVA_SNAPTOGRID not implemented
 56  *   -- LISTVIEW_ApproximateViewRect partially implemented
 57  *   -- LISTVIEW_[GS]etColumnOrderArray stubs
 58  *   -- LISTVIEW_SetColumnWidth ignores header images & bitmap
 59  *   -- LISTVIEW_SetIconSpacing is incomplete
 60  *   -- LISTVIEW_SortItems is broken
 61  *   -- LISTVIEW_StyleChanged doesn't handle some changes too well
 62  *
 63  * Speedups
 64  *   -- LISTVIEW_GetNextItem needs to be rewritten. It is currently
 65  *      linear in the number of items in the list, and this is
 66  *      unacceptable for large lists.
 67  *   -- in sorted mode, LISTVIEW_InsertItemT sorts the array,
 68  *      instead of inserting in the right spot
 69  *   -- we should keep an ordered array of coordinates in iconic mode
 70  *      this would allow to frame items (iterator_frameditems),
 71  *      and find nearest item (LVFI_NEARESTXY) a lot more efficiently
 72  *
 73  * Flags
 74  *   -- LVIF_COLUMNS
 75  *   -- LVIF_GROUPID
 76  *   -- LVIF_NORECOMPUTE
 77  *
 78  * States
 79  *   -- LVIS_ACTIVATING (not currently supported by comctl32.dll version 6.0)
 80  *   -- LVIS_CUT
 81  *   -- LVIS_DROPHILITED
 82  *   -- LVIS_OVERLAYMASK
 83  *
 84  * Styles
 85  *   -- LVS_NOLABELWRAP
 86  *   -- LVS_NOSCROLL (see Q137520)
 87  *   -- LVS_SORTASCENDING, LVS_SORTDESCENDING
 88  *   -- LVS_ALIGNTOP
 89  *   -- LVS_TYPESTYLEMASK
 90  *
 91  * Extended Styles
 92  *   -- LVS_EX_BORDERSELECT
 93  *   -- LVS_EX_FLATSB
 94  *   -- LVS_EX_HEADERDRAGDROP
 95  *   -- LVS_EX_INFOTIP
 96  *   -- LVS_EX_LABELTIP
 97  *   -- LVS_EX_MULTIWORKAREAS
 98  *   -- LVS_EX_ONECLICKACTIVATE
 99  *   -- LVS_EX_REGIONAL
100  *   -- LVS_EX_SIMPLESELECT
101  *   -- LVS_EX_TRACKSELECT
102  *   -- LVS_EX_TWOCLICKACTIVATE
103  *   -- LVS_EX_UNDERLINECOLD
104  *   -- LVS_EX_UNDERLINEHOT
105  *   
106  * Notifications:
107  *   -- LVN_BEGINSCROLL, LVN_ENDSCROLL
108  *   -- LVN_GETINFOTIP
109  *   -- LVN_HOTTRACK
110  *   -- LVN_MARQUEEBEGIN
111  *   -- LVN_ODFINDITEM
112  *   -- LVN_SETDISPINFO
113  *   -- NM_HOVER
114  *   -- LVN_BEGINRDRAG
115  *
116  * Messages:
117  *   -- LVM_CANCELEDITLABEL
118  *   -- LVM_ENABLEGROUPVIEW
119  *   -- LVM_GETBKIMAGE, LVM_SETBKIMAGE
120  *   -- LVM_GETGROUPINFO, LVM_SETGROUPINFO
121  *   -- LVM_GETGROUPMETRICS, LVM_SETGROUPMETRICS
122  *   -- LVM_GETINSERTMARK, LVM_SETINSERTMARK
123  *   -- LVM_GETINSERTMARKCOLOR, LVM_SETINSERTMARKCOLOR
124  *   -- LVM_GETINSERTMARKRECT
125  *   -- LVM_GETNUMBEROFWORKAREAS
126  *   -- LVM_GETOUTLINECOLOR, LVM_SETOUTLINECOLOR
127  *   -- LVM_GETSELECTEDCOLUMN, LVM_SETSELECTEDCOLUMN
128  *   -- LVM_GETISEARCHSTRINGW, LVM_GETISEARCHSTRINGA
129  *   -- LVM_GETTILEINFO, LVM_SETTILEINFO
130  *   -- LVM_GETTILEVIEWINFO, LVM_SETTILEVIEWINFO
131  *   -- LVM_GETUNICODEFORMAT, LVM_SETUNICODEFORMAT
132  *   -- LVM_GETVIEW, LVM_SETVIEW
133  *   -- LVM_GETWORKAREAS, LVM_SETWORKAREAS
134  *   -- LVM_HASGROUP, LVM_INSERTGROUP, LVM_REMOVEGROUP, LVM_REMOVEALLGROUPS
135  *   -- LVM_INSERTGROUPSORTED
136  *   -- LVM_INSERTMARKHITTEST
137  *   -- LVM_ISGROUPVIEWENABLED
138  *   -- LVM_MAPIDTOINDEX, LVM_MAPINDEXTOID
139  *   -- LVM_MOVEGROUP
140  *   -- LVM_MOVEITEMTOGROUP
141  *   -- LVM_SETINFOTIP
142  *   -- LVM_SETTILEWIDTH
143  *   -- LVM_SORTGROUPS
144  *   -- LVM_SORTITEMSEX
145  *
146  * Macros:
147  *   -- ListView_GetCheckSate, ListView_SetCheckState
148  *   -- ListView_GetHoverTime, ListView_SetHoverTime
149  *   -- ListView_GetISearchString
150  *   -- ListView_GetNumberOfWorkAreas
151  *   -- ListView_GetOrigin
152  *   -- ListView_GetTextBkColor
153  *   -- ListView_GetUnicodeFormat, ListView_SetUnicodeFormat
154  *   -- ListView_GetWorkAreas, ListView_SetWorkAreas
155  *   -- ListView_SortItemsEx
156  *
157  * Functions:
158  *   -- LVGroupComparE
159  *
160  * Known differences in message stream from native control (not known if
161  * these differences cause problems):
162  *   LVM_INSERTITEM issues LVM_SETITEMSTATE and LVM_SETITEM in certain cases.
163  *   LVM_SETITEM does not always issue LVN_ITEMCHANGING/LVN_ITEMCHANGED.
164  *   WM_CREATE does not issue WM_QUERYUISTATE and associated registry
165  *     processing for "USEDOUBLECLICKTIME".
166  */
167 
168 #include "config.h"
169 #include "wine/port.h"
170 
171 #include <assert.h>
172 #include <ctype.h>
173 #include <string.h>
174 #include <stdlib.h>
175 #include <stdarg.h>
176 #include <stdio.h>
177 
178 #include "windef.h"
179 #include "winbase.h"
180 #include "winnt.h"
181 #include "wingdi.h"
182 #include "winuser.h"
183 #include "winnls.h"
184 #include "commctrl.h"
185 #include "comctl32.h"
186 #include "uxtheme.h"
187 
188 #include "wine/debug.h"
189 #include "wine/unicode.h"
190 
191 WINE_DEFAULT_DEBUG_CHANNEL(listview);
192 
193 /* make sure you set this to 0 for production use! */
194 #define DEBUG_RANGES 1
195 
196 typedef struct tagCOLUMN_INFO
197 {
198   RECT rcHeader;        /* tracks the header's rectangle */
199   int fmt;              /* same as LVCOLUMN.fmt */
200 } COLUMN_INFO;
201 
202 typedef struct tagITEMHDR
203 {
204   LPWSTR pszText;
205   INT iImage;
206 } ITEMHDR, *LPITEMHDR;
207 
208 typedef struct tagSUBITEM_INFO
209 {
210   ITEMHDR hdr;
211   INT iSubItem;
212 } SUBITEM_INFO;
213 
214 typedef struct tagITEM_INFO
215 {
216   ITEMHDR hdr;
217   UINT state;
218   LPARAM lParam;
219   INT iIndent;
220 } ITEM_INFO;
221 
222 typedef struct tagRANGE
223 {
224   INT lower;
225   INT upper;
226 } RANGE;
227 
228 typedef struct tagRANGES
229 {
230   HDPA hdpa;
231 } *RANGES;
232 
233 typedef struct tagITERATOR
234 {
235   INT nItem;
236   INT nSpecial;
237   RANGE range;
238   RANGES ranges;
239   INT index;
240 } ITERATOR;
241 
242 typedef struct tagDELAYED_ITEM_EDIT
243 {
244   BOOL fEnabled;
245   INT iItem;
246 } DELAYED_ITEM_EDIT;
247 
248 typedef struct tagLISTVIEW_INFO
249 {
250   HWND hwndSelf;
251   HBRUSH hBkBrush;
252   COLORREF clrBk;
253   COLORREF clrText;
254   COLORREF clrTextBk;
255   HIMAGELIST himlNormal;
256   HIMAGELIST himlSmall;
257   HIMAGELIST himlState;
258   BOOL bLButtonDown;
259   BOOL bRButtonDown;
260   BOOL bDragging;
261   POINT ptClickPos;         /* point where the user clicked */ 
262   BOOL bNoItemMetrics;          /* flags if item metrics are not yet computed */
263   INT nItemHeight;
264   INT nItemWidth;
265   RANGES selectionRanges;
266   INT nSelectionMark;
267   INT nHotItem;
268   SHORT notifyFormat;
269   HWND hwndNotify;
270   RECT rcList;                 /* This rectangle is really the window
271                                 * client rectangle possibly reduced by the 
272                                 * horizontal scroll bar and/or header - see 
273                                 * LISTVIEW_UpdateSize. This rectangle offset
274                                 * by the LISTVIEW_GetOrigin value is in
275                                 * client coordinates   */
276   SIZE iconSize;
277   SIZE iconSpacing;
278   SIZE iconStateSize;
279   UINT uCallbackMask;
280   HWND hwndHeader;
281   HCURSOR hHotCursor;
282   HFONT hDefaultFont;
283   HFONT hFont;
284   INT ntmHeight;                /* Some cached metrics of the font used */
285   INT ntmMaxCharWidth;          /* by the listview to draw items */
286   INT nEllipsisWidth;
287   BOOL bRedraw;                 /* Turns on/off repaints & invalidations */
288   BOOL bAutoarrange;            /* Autoarrange flag when NOT in LVS_AUTOARRANGE */
289   BOOL bFocus;
290   BOOL bDoChangeNotify;         /* send change notification messages? */
291   INT nFocusedItem;
292   RECT rcFocus;
293   DWORD dwStyle;                /* the cached window GWL_STYLE */
294   DWORD dwLvExStyle;            /* extended listview style */
295   INT nItemCount;               /* the number of items in the list */
296   HDPA hdpaItems;               /* array ITEM_INFO pointers */
297   HDPA hdpaPosX;                /* maintains the (X, Y) coordinates of the */
298   HDPA hdpaPosY;                /* items in LVS_ICON, and LVS_SMALLICON modes */
299   HDPA hdpaColumns;             /* array of COLUMN_INFO pointers */
300   POINT currIconPos;            /* this is the position next icon will be placed */
301   PFNLVCOMPARE pfnCompare;
302   LPARAM lParamSort;
303   HWND hwndEdit;
304   WNDPROC EditWndProc;
305   INT nEditLabelItem;
306   DWORD dwHoverTime;
307   HWND hwndToolTip;
308 
309   DWORD cditemmode;             /* Keep the custom draw flags for an item/row */
310 
311   DWORD lastKeyPressTimestamp;
312   WPARAM charCode;
313   INT nSearchParamLength;
314   WCHAR szSearchParam[ MAX_PATH ];
315   BOOL bIsDrawing;
316   INT nMeasureItemHeight;
317   INT xTrackLine;               /* The x coefficient of the track line or -1 if none */
318   DELAYED_ITEM_EDIT itemEdit;   /* Pointer to this structure will be the timer ID */
319 } LISTVIEW_INFO;
320 
321 /*
322  * constants
323  */
324 /* How many we debug buffer to allocate */
325 #define DEBUG_BUFFERS 20
326 /* The size of a single debug bbuffer */
327 #define DEBUG_BUFFER_SIZE 256
328 
329 /* Internal interface to LISTVIEW_HScroll and LISTVIEW_VScroll */
330 #define SB_INTERNAL      -1
331 
332 /* maximum size of a label */
333 #define DISP_TEXT_SIZE 512
334 
335 /* padding for items in list and small icon display modes */
336 #define WIDTH_PADDING 12
337 
338 /* padding for items in list, report and small icon display modes */
339 #define HEIGHT_PADDING 1
340 
341 /* offset of items in report display mode */
342 #define REPORT_MARGINX 2
343 
344 /* padding for icon in large icon display mode
345  *   ICON_TOP_PADDING_NOTHITABLE - space between top of box and area
346  *                                 that HITTEST will see.
347  *   ICON_TOP_PADDING_HITABLE - spacing between above and icon.
348  *   ICON_TOP_PADDING - sum of the two above.
349  *   ICON_BOTTOM_PADDING - between bottom of icon and top of text
350  *   LABEL_HOR_PADDING - between text and sides of box
351  *   LABEL_VERT_PADDING - between bottom of text and end of box
352  *
353  *   ICON_LR_PADDING - additional width above icon size.
354  *   ICON_LR_HALF - half of the above value
355  */
356 #define ICON_TOP_PADDING_NOTHITABLE  2
357 #define ICON_TOP_PADDING_HITABLE     2
358 #define ICON_TOP_PADDING (ICON_TOP_PADDING_NOTHITABLE + ICON_TOP_PADDING_HITABLE)
359 #define ICON_BOTTOM_PADDING          4
360 #define LABEL_HOR_PADDING            5
361 #define LABEL_VERT_PADDING           7
362 #define ICON_LR_PADDING              16
363 #define ICON_LR_HALF                 (ICON_LR_PADDING/2)
364 
365 /* default label width for items in list and small icon display modes */
366 #define DEFAULT_LABEL_WIDTH 40
367 
368 /* default column width for items in list display mode */
369 #define DEFAULT_COLUMN_WIDTH 128
370 
371 /* Size of "line" scroll for V & H scrolls */
372 #define LISTVIEW_SCROLL_ICON_LINE_SIZE 37
373 
374 /* Padding between image and label */
375 #define IMAGE_PADDING  2
376 
377 /* Padding behind the label */
378 #define TRAILING_LABEL_PADDING  12
379 #define TRAILING_HEADER_PADDING  11
380 
381 /* Border for the icon caption */
382 #define CAPTION_BORDER  2
383 
384 /* Standard DrawText flags */
385 #define LV_ML_DT_FLAGS  (DT_TOP | DT_NOPREFIX | DT_EDITCONTROL | DT_CENTER | DT_WORDBREAK | DT_WORD_ELLIPSIS | DT_END_ELLIPSIS)
386 #define LV_FL_DT_FLAGS  (DT_TOP | DT_NOPREFIX | DT_EDITCONTROL | DT_CENTER | DT_WORDBREAK | DT_NOCLIP)
387 #define LV_SL_DT_FLAGS  (DT_VCENTER | DT_NOPREFIX | DT_EDITCONTROL | DT_SINGLELINE | DT_WORD_ELLIPSIS | DT_END_ELLIPSIS)
388 
389 /* Image index from state */
390 #define STATEIMAGEINDEX(x) (((x) & LVIS_STATEIMAGEMASK) >> 12)
391 
392 /* The time in milliseconds to reset the search in the list */
393 #define KEY_DELAY       450
394 
395 /* Dump the LISTVIEW_INFO structure to the debug channel */
396 #define LISTVIEW_DUMP(iP) do { \
397   TRACE("hwndSelf=%p, clrBk=0x%06x, clrText=0x%06x, clrTextBk=0x%06x, ItemHeight=%d, ItemWidth=%d, Style=0x%08x\n", \
398         iP->hwndSelf, iP->clrBk, iP->clrText, iP->clrTextBk, \
399         iP->nItemHeight, iP->nItemWidth, iP->dwStyle); \
400   TRACE("hwndSelf=%p, himlNor=%p, himlSml=%p, himlState=%p, Focused=%d, Hot=%d, exStyle=0x%08x, Focus=%d\n", \
401         iP->hwndSelf, iP->himlNormal, iP->himlSmall, iP->himlState, \
402         iP->nFocusedItem, iP->nHotItem, iP->dwLvExStyle, iP->bFocus ); \
403   TRACE("hwndSelf=%p, ntmH=%d, icSz.cx=%d, icSz.cy=%d, icSp.cx=%d, icSp.cy=%d, notifyFmt=%d\n", \
404         iP->hwndSelf, iP->ntmHeight, iP->iconSize.cx, iP->iconSize.cy, \
405         iP->iconSpacing.cx, iP->iconSpacing.cy, iP->notifyFormat); \
406   TRACE("hwndSelf=%p, rcList=%s\n", iP->hwndSelf, wine_dbgstr_rect(&iP->rcList)); \
407 } while(0)
408 
409 static const WCHAR themeClass[] = {'L','i','s','t','V','i','e','w',0};
410 
411 /*
412  * forward declarations
413  */
414 static BOOL LISTVIEW_GetItemT(const LISTVIEW_INFO *, LPLVITEMW, BOOL);
415 static void LISTVIEW_GetItemBox(const LISTVIEW_INFO *, INT, LPRECT);
416 static void LISTVIEW_GetItemOrigin(const LISTVIEW_INFO *, INT, LPPOINT);
417 static BOOL LISTVIEW_GetItemPosition(const LISTVIEW_INFO *, INT, LPPOINT);
418 static BOOL LISTVIEW_GetItemRect(const LISTVIEW_INFO *, INT, LPRECT);
419 static INT LISTVIEW_GetLabelWidth(const LISTVIEW_INFO *, INT);
420 static void LISTVIEW_GetOrigin(const LISTVIEW_INFO *, LPPOINT);
421 static BOOL LISTVIEW_GetViewRect(const LISTVIEW_INFO *, LPRECT);
422 static void LISTVIEW_SetGroupSelection(LISTVIEW_INFO *, INT);
423 static BOOL LISTVIEW_SetItemT(LISTVIEW_INFO *, LVITEMW *, BOOL);
424 static void LISTVIEW_UpdateScroll(const LISTVIEW_INFO *);
425 static void LISTVIEW_SetSelection(LISTVIEW_INFO *, INT);
426 static void LISTVIEW_UpdateSize(LISTVIEW_INFO *);
427 static HWND LISTVIEW_EditLabelT(LISTVIEW_INFO *, INT, BOOL);
428 static LRESULT LISTVIEW_Command(const LISTVIEW_INFO *, WPARAM, LPARAM);
429 static BOOL LISTVIEW_SortItems(LISTVIEW_INFO *, PFNLVCOMPARE, LPARAM);
430 static INT LISTVIEW_GetStringWidthT(const LISTVIEW_INFO *, LPCWSTR, BOOL);
431 static BOOL LISTVIEW_KeySelection(LISTVIEW_INFO *, INT);
432 static UINT LISTVIEW_GetItemState(const LISTVIEW_INFO *, INT, UINT);
433 static BOOL LISTVIEW_SetItemState(LISTVIEW_INFO *, INT, const LVITEMW *);
434 static LRESULT LISTVIEW_VScroll(LISTVIEW_INFO *, INT, INT, HWND);
435 static LRESULT LISTVIEW_HScroll(LISTVIEW_INFO *, INT, INT, HWND);
436 static INT LISTVIEW_GetTopIndex(const LISTVIEW_INFO *);
437 static BOOL LISTVIEW_EnsureVisible(LISTVIEW_INFO *, INT, BOOL);
438 static HWND CreateEditLabelT(LISTVIEW_INFO *, LPCWSTR, DWORD, INT, INT, INT, INT, BOOL);
439 static HIMAGELIST LISTVIEW_SetImageList(LISTVIEW_INFO *, INT, HIMAGELIST);
440 static INT LISTVIEW_HitTest(const LISTVIEW_INFO *, LPLVHITTESTINFO, BOOL, BOOL);
441 
442 /******** Text handling functions *************************************/
443 
444 /* A text pointer is either NULL, LPSTR_TEXTCALLBACK, or points to a
445  * text string. The string may be ANSI or Unicode, in which case
446  * the boolean isW tells us the type of the string.
447  *
448  * The name of the function tell what type of strings it expects:
449  *   W: Unicode, T: ANSI/Unicode - function of isW
450  */
451 
452 static inline BOOL is_textW(LPCWSTR text)
453 {
454     return text != NULL && text != LPSTR_TEXTCALLBACKW;
455 }
456 
457 static inline BOOL is_textT(LPCWSTR text, BOOL isW)
458 {
459     /* we can ignore isW since LPSTR_TEXTCALLBACKW == LPSTR_TEXTCALLBACKA */
460     return is_textW(text);
461 }
462 
463 static inline int textlenT(LPCWSTR text, BOOL isW)
464 {
465     return !is_textT(text, isW) ? 0 :
466            isW ? lstrlenW(text) : lstrlenA((LPCSTR)text);
467 }
468 
469 static inline void textcpynT(LPWSTR dest, BOOL isDestW, LPCWSTR src, BOOL isSrcW, INT max)
470 {
471     if (isDestW)
472         if (isSrcW) lstrcpynW(dest, src, max);
473         else MultiByteToWideChar(CP_ACP, 0, (LPCSTR)src, -1, dest, max);
474     else
475         if (isSrcW) WideCharToMultiByte(CP_ACP, 0, src, -1, (LPSTR)dest, max, NULL, NULL);
476         else lstrcpynA((LPSTR)dest, (LPCSTR)src, max);
477 }
478 
479 static inline LPWSTR textdupTtoW(LPCWSTR text, BOOL isW)
480 {
481     LPWSTR wstr = (LPWSTR)text;
482 
483     if (!isW && is_textT(text, isW))
484     {
485         INT len = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)text, -1, NULL, 0);
486         wstr = Alloc(len * sizeof(WCHAR));
487         if (wstr) MultiByteToWideChar(CP_ACP, 0, (LPCSTR)text, -1, wstr, len);
488     }
489     TRACE("   wstr=%s\n", text == LPSTR_TEXTCALLBACKW ?  "(callback)" : debugstr_w(wstr));
490     return wstr;
491 }
492 
493 static inline void textfreeT(LPWSTR wstr, BOOL isW)
494 {
495     if (!isW && is_textT(wstr, isW)) Free (wstr);
496 }
497 
498 /*
499  * dest is a pointer to a Unicode string
500  * src is a pointer to a string (Unicode if isW, ANSI if !isW)
501  */
502 static BOOL textsetptrT(LPWSTR *dest, LPCWSTR src, BOOL isW)
503 {
504     BOOL bResult = TRUE;
505     
506     if (src == LPSTR_TEXTCALLBACKW)
507     {
508         if (is_textW(*dest)) Free(*dest);
509         *dest = LPSTR_TEXTCALLBACKW;
510     }
511     else
512     {
513         LPWSTR pszText = textdupTtoW(src, isW);
514         if (*dest == LPSTR_TEXTCALLBACKW) *dest = NULL;
515         bResult = Str_SetPtrW(dest, pszText);
516         textfreeT(pszText, isW);
517     }
518     return bResult;
519 }
520 
521 /*
522  * compares a Unicode to a Unicode/ANSI text string
523  */
524 static inline int textcmpWT(LPCWSTR aw, LPCWSTR bt, BOOL isW)
525 {
526     if (!aw) return bt ? -1 : 0;
527     if (!bt) return aw ? 1 : 0;
528     if (aw == LPSTR_TEXTCALLBACKW)
529         return bt == LPSTR_TEXTCALLBACKW ? 0 : -1;
530     if (bt != LPSTR_TEXTCALLBACKW)
531     {
532         LPWSTR bw = textdupTtoW(bt, isW);
533         int r = bw ? lstrcmpW(aw, bw) : 1;
534         textfreeT(bw, isW);
535         return r;
536     }       
537             
538     return 1;
539 }
540     
541 static inline int lstrncmpiW(LPCWSTR s1, LPCWSTR s2, int n)
542 {
543     int res;
544 
545     n = min(min(n, lstrlenW(s1)), lstrlenW(s2));
546     res = CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE, s1, n, s2, n);
547     return res ? res - sizeof(WCHAR) : res;
548 }
549 
550 /******** Debugging functions *****************************************/
551 
552 static inline LPCSTR debugtext_t(LPCWSTR text, BOOL isW)
553 {
554     if (text == LPSTR_TEXTCALLBACKW) return "(callback)";
555     return isW ? debugstr_w(text) : debugstr_a((LPCSTR)text);
556 }
557 
558 static inline LPCSTR debugtext_tn(LPCWSTR text, BOOL isW, INT n)
559 {
560     if (text == LPSTR_TEXTCALLBACKW) return "(callback)";
561     n = min(textlenT(text, isW), n);
562     return isW ? debugstr_wn(text, n) : debugstr_an((LPCSTR)text, n);
563 }
564 
565 static char* debug_getbuf(void)
566 {
567     static int index = 0;
568     static char buffers[DEBUG_BUFFERS][DEBUG_BUFFER_SIZE];
569     return buffers[index++ % DEBUG_BUFFERS];
570 }
571 
572 static inline const char* debugrange(const RANGE *lprng)
573 {
574     if (!lprng) return "(null)";
575     return wine_dbg_sprintf("[%d, %d]", lprng->lower, lprng->upper);
576 }
577 
578 static const char* debugscrollinfo(const SCROLLINFO *pScrollInfo)
579 {
580     char* buf = debug_getbuf(), *text = buf;
581     int len, size = DEBUG_BUFFER_SIZE;
582 
583     if (pScrollInfo == NULL) return "(null)";
584     len = snprintf(buf, size, "{cbSize=%d, ", pScrollInfo->cbSize);
585     if (len == -1) goto end; buf += len; size -= len;
586     if (pScrollInfo->fMask & SIF_RANGE)
587         len = snprintf(buf, size, "nMin=%d, nMax=%d, ", pScrollInfo->nMin, pScrollInfo->nMax);
588     else len = 0;
589     if (len == -1) goto end; buf += len; size -= len;
590     if (pScrollInfo->fMask & SIF_PAGE)
591         len = snprintf(buf, size, "nPage=%u, ", pScrollInfo->nPage);
592     else len = 0;
593     if (len == -1) goto end; buf += len; size -= len;
594     if (pScrollInfo->fMask & SIF_POS)
595         len = snprintf(buf, size, "nPos=%d, ", pScrollInfo->nPos);
596     else len = 0;
597     if (len == -1) goto end; buf += len; size -= len;
598     if (pScrollInfo->fMask & SIF_TRACKPOS)
599         len = snprintf(buf, size, "nTrackPos=%d, ", pScrollInfo->nTrackPos);
600     else len = 0;
601     if (len == -1) goto end; buf += len; size -= len;
602     goto undo;
603 end:
604     buf = text + strlen(text);
605 undo:
606     if (buf - text > 2) { buf[-2] = '}'; buf[-1] = 0; }
607     return text;
608 } 
609 
610 static const char* debugnmlistview(const NMLISTVIEW *plvnm)
611 {
612     if (!plvnm) return "(null)";
613     return wine_dbg_sprintf("iItem=%d, iSubItem=%d, uNewState=0x%x,"
614                  " uOldState=0x%x, uChanged=0x%x, ptAction=%s, lParam=%ld",
615                  plvnm->iItem, plvnm->iSubItem, plvnm->uNewState, plvnm->uOldState,
616                  plvnm->uChanged, wine_dbgstr_point(&plvnm->ptAction), plvnm->lParam);
617 }
618 
619 static const char* debuglvitem_t(const LVITEMW *lpLVItem, BOOL isW)
620 {
621     char* buf = debug_getbuf(), *text = buf;
622     int len, size = DEBUG_BUFFER_SIZE;
623     
624     if (lpLVItem == NULL) return "(null)";
625     len = snprintf(buf, size, "{iItem=%d, iSubItem=%d, ", lpLVItem->iItem, lpLVItem->iSubItem);
626     if (len == -1) goto end; buf += len; size -= len;
627     if (lpLVItem->mask & LVIF_STATE)
628         len = snprintf(buf, size, "state=%x, stateMask=%x, ", lpLVItem->state, lpLVItem->stateMask);
629     else len = 0;
630     if (len == -1) goto end; buf += len; size -= len;
631     if (lpLVItem->mask & LVIF_TEXT)
632         len = snprintf(buf, size, "pszText=%s, cchTextMax=%d, ", debugtext_tn(lpLVItem->pszText, isW, 80), lpLVItem->cchTextMax);
633     else len = 0;
634     if (len == -1) goto end; buf += len; size -= len;
635     if (lpLVItem->mask & LVIF_IMAGE)
636         len = snprintf(buf, size, "iImage=%d, ", lpLVItem->iImage);
637     else len = 0;
638     if (len == -1) goto end; buf += len; size -= len;
639     if (lpLVItem->mask & LVIF_PARAM)
640         len = snprintf(buf, size, "lParam=%lx, ", lpLVItem->lParam);
641     else len = 0;
642     if (len == -1) goto end; buf += len; size -= len;
643     if (lpLVItem->mask & LVIF_INDENT)
644         len = snprintf(buf, size, "iIndent=%d, ", lpLVItem->iIndent);
645     else len = 0;
646     if (len == -1) goto end; buf += len; size -= len;
647     goto undo;
648 end:
649     buf = text + strlen(text);
650 undo:
651     if (buf - text > 2) { buf[-2] = '}'; buf[-1] = 0; }
652     return text;
653 }
654 
655 static const char* debuglvcolumn_t(const LVCOLUMNW *lpColumn, BOOL isW)
656 {
657     char* buf = debug_getbuf(), *text = buf;
658     int len, size = DEBUG_BUFFER_SIZE;
659     
660     if (lpColumn == NULL) return "(null)";
661     len = snprintf(buf, size, "{");
662     if (len == -1) goto end; buf += len; size -= len;
663     if (lpColumn->mask & LVCF_SUBITEM)
664         len = snprintf(buf, size, "iSubItem=%d, ",  lpColumn->iSubItem);
665     else len = 0;
666     if (len == -1) goto end; buf += len; size -= len;
667     if (lpColumn->mask & LVCF_FMT)
668         len = snprintf(buf, size, "fmt=%x, ", lpColumn->fmt);
669     else len = 0;
670     if (len == -1) goto end; buf += len; size -= len;
671     if (lpColumn->mask & LVCF_WIDTH)
672         len = snprintf(buf, size, "cx=%d, ", lpColumn->cx);
673     else len = 0;
674     if (len == -1) goto end; buf += len; size -= len;
675     if (lpColumn->mask & LVCF_TEXT)
676         len = snprintf(buf, size, "pszText=%s, cchTextMax=%d, ", debugtext_tn(lpColumn->pszText, isW, 80), lpColumn->cchTextMax);
677     else len = 0;
678     if (len == -1) goto end; buf += len; size -= len;
679     if (lpColumn->mask & LVCF_IMAGE)
680         len = snprintf(buf, size, "iImage=%d, ", lpColumn->iImage);
681     else len = 0;
682     if (len == -1) goto end; buf += len; size -= len;
683     if (lpColumn->mask & LVCF_ORDER)
684         len = snprintf(buf, size, "iOrder=%d, ", lpColumn->iOrder);
685     else len = 0;
686     if (len == -1) goto end; buf += len; size -= len;
687     goto undo;
688 end:
689     buf = text + strlen(text);
690 undo:
691     if (buf - text > 2) { buf[-2] = '}'; buf[-1] = 0; }
692     return text;
693 }
694 
695 static const char* debuglvhittestinfo(const LVHITTESTINFO *lpht)
696 {
697     if (!lpht) return "(null)";
698 
699     return wine_dbg_sprintf("{pt=%s, flags=0x%x, iItem=%d, iSubItem=%d}",
700                  wine_dbgstr_point(&lpht->pt), lpht->flags, lpht->iItem, lpht->iSubItem);
701 }
702 
703 /* Return the corresponding text for a given scroll value */
704 static inline LPCSTR debugscrollcode(int nScrollCode)
705 {
706   switch(nScrollCode)
707   {
708   case SB_LINELEFT: return "SB_LINELEFT";
709   case SB_LINERIGHT: return "SB_LINERIGHT";
710   case SB_PAGELEFT: return "SB_PAGELEFT";
711   case SB_PAGERIGHT: return "SB_PAGERIGHT";
712   case SB_THUMBPOSITION: return "SB_THUMBPOSITION";
713   case SB_THUMBTRACK: return "SB_THUMBTRACK";
714   case SB_ENDSCROLL: return "SB_ENDSCROLL";
715   case SB_INTERNAL: return "SB_INTERNAL";
716   default: return "unknown";
717   }
718 }
719 
720 
721 /******** Notification functions i************************************/
722 
723 static LRESULT notify_forward_header(const LISTVIEW_INFO *infoPtr, const NMHEADERW *lpnmh)
724 {
725     return SendMessageW(infoPtr->hwndNotify, WM_NOTIFY,
726                         (WPARAM)lpnmh->hdr.idFrom, (LPARAM)lpnmh);
727 }
728 
729 static LRESULT notify_hdr(const LISTVIEW_INFO *infoPtr, INT code, LPNMHDR pnmh)
730 {
731     LRESULT result;
732     
733     TRACE("(code=%d)\n", code);
734 
735     pnmh->hwndFrom = infoPtr->hwndSelf;
736     pnmh->idFrom = GetWindowLongPtrW(infoPtr->hwndSelf, GWLP_ID);
737     pnmh->code = code;
738     result = SendMessageW(infoPtr->hwndNotify, WM_NOTIFY, pnmh->idFrom, (LPARAM)pnmh);
739 
740     TRACE("  <= %ld\n", result);
741 
742     return result;
743 }
744 
745 static inline BOOL notify(const LISTVIEW_INFO *infoPtr, INT code)
746 {
747     NMHDR nmh;
748     HWND hwnd = infoPtr->hwndSelf;
749     notify_hdr(infoPtr, code, &nmh);
750     return IsWindow(hwnd);
751 }
752 
753 static inline void notify_itemactivate(const LISTVIEW_INFO *infoPtr, const LVHITTESTINFO *htInfo)
754 {
755     NMITEMACTIVATE nmia;
756     LVITEMW item;
757 
758     if (htInfo) {
759       nmia.uNewState = 0;
760       nmia.uOldState = 0;
761       nmia.uChanged  = 0;
762       nmia.uKeyFlags = 0;
763       
764       item.mask = LVIF_PARAM|LVIF_STATE;
765       item.iItem = htInfo->iItem;
766       item.iSubItem = 0;
767       if (LISTVIEW_GetItemT(infoPtr, &item, TRUE)) {
768           nmia.lParam = item.lParam;
769           nmia.uOldState = item.state;
770           nmia.uNewState = item.state | LVIS_ACTIVATING;
771           nmia.uChanged  = LVIF_STATE;
772       }
773       
774       nmia.iItem = htInfo->iItem;
775       nmia.iSubItem = htInfo->iSubItem;
776       nmia.ptAction = htInfo->pt;     
777       
778       if (GetKeyState(VK_SHIFT) & 0x8000) nmia.uKeyFlags |= LVKF_SHIFT;
779       if (GetKeyState(VK_CONTROL) & 0x8000) nmia.uKeyFlags |= LVKF_CONTROL;
780       if (GetKeyState(VK_MENU) & 0x8000) nmia.uKeyFlags |= LVKF_ALT;
781     }
782     notify_hdr(infoPtr, LVN_ITEMACTIVATE, (LPNMHDR)&nmia);
783 }
784 
785 static inline LRESULT notify_listview(const LISTVIEW_INFO *infoPtr, INT code, LPNMLISTVIEW plvnm)
786 {
787     TRACE("(code=%d, plvnm=%s)\n", code, debugnmlistview(plvnm));
788     return notify_hdr(infoPtr, code, (LPNMHDR)plvnm);
789 }
790 
791 static BOOL notify_click(const LISTVIEW_INFO *infoPtr, INT code, const LVHITTESTINFO *lvht)
792 {
793     NMLISTVIEW nmlv;
794     LVITEMW item;
795     HWND hwnd = infoPtr->hwndSelf;
796 
797     TRACE("code=%d, lvht=%s\n", code, debuglvhittestinfo(lvht)); 
798     ZeroMemory(&nmlv, sizeof(nmlv));
799     nmlv.iItem = lvht->iItem;
800     nmlv.iSubItem = lvht->iSubItem;
801     nmlv.ptAction = lvht->pt;
802     item.mask = LVIF_PARAM;
803     item.iItem = lvht->iItem;
804     item.iSubItem = 0;
805     if (LISTVIEW_GetItemT(infoPtr, &item, TRUE)) nmlv.lParam = item.lParam;
806     notify_listview(infoPtr, code, &nmlv);
807     return IsWindow(hwnd);
808 }
809 
810 static BOOL notify_deleteitem(const LISTVIEW_INFO *infoPtr, INT nItem)
811 {
812     NMLISTVIEW nmlv;
813     LVITEMW item;
814     HWND hwnd = infoPtr->hwndSelf;
815 
816     ZeroMemory(&nmlv, sizeof (NMLISTVIEW));
817     nmlv.iItem = nItem;
818     item.mask = LVIF_PARAM;
819     item.iItem = nItem;
820     item.iSubItem = 0;
821     if (LISTVIEW_GetItemT(infoPtr, &item, TRUE)) nmlv.lParam = item.lParam;
822     notify_listview(infoPtr, LVN_DELETEITEM, &nmlv);
823     return IsWindow(hwnd);
824 }
825 
826 static int get_ansi_notification(UINT unicodeNotificationCode)
827 {
828     switch (unicodeNotificationCode)
829     {
830     case LVN_BEGINLABELEDITW: return LVN_BEGINLABELEDITA;
831     case LVN_ENDLABELEDITW: return LVN_ENDLABELEDITA;
832     case LVN_GETDISPINFOW: return LVN_GETDISPINFOA;
833     case LVN_SETDISPINFOW: return LVN_SETDISPINFOA;
834     case LVN_ODFINDITEMW: return LVN_ODFINDITEMA;
835     case LVN_GETINFOTIPW: return LVN_GETINFOTIPA;
836     }
837     ERR("unknown notification %x\n", unicodeNotificationCode);
838     assert(FALSE);
839     return 0;
840 }
841 
842 /*
843   Send notification. depends on dispinfoW having same
844   structure as dispinfoA.
845   infoPtr : listview struct
846   notificationCode : *Unicode* notification code
847   pdi : dispinfo structure (can be unicode or ansi)
848   isW : TRUE if dispinfo is Unicode
849 */
850 static BOOL notify_dispinfoT(const LISTVIEW_INFO *infoPtr, UINT notificationCode, LPNMLVDISPINFOW pdi, BOOL isW)
851 {
852     BOOL bResult = FALSE;
853     BOOL convertToAnsi = FALSE, convertToUnicode = FALSE;
854     INT cchTempBufMax = 0, savCchTextMax = 0;
855     UINT realNotifCode;
856     LPWSTR pszTempBuf = NULL, savPszText = NULL;
857 
858     if ((pdi->item.mask & LVIF_TEXT) && is_textT(pdi->item.pszText, isW))
859     {
860         convertToAnsi = (isW && infoPtr->notifyFormat == NFR_ANSI);
861         convertToUnicode = (!isW && infoPtr->notifyFormat == NFR_UNICODE);
862     }
863 
864     if (convertToAnsi || convertToUnicode)
865     {
866         if (notificationCode != LVN_GETDISPINFOW)
867         {
868             cchTempBufMax = convertToUnicode ?
869                 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)pdi->item.pszText, -1, NULL, 0):
870                 WideCharToMultiByte(CP_ACP, 0, pdi->item.pszText, -1, NULL, 0, NULL, NULL);
871         }
872         else
873         {
874             cchTempBufMax = pdi->item.cchTextMax;
875             *pdi->item.pszText = 0; /* make sure we don't process garbage */
876         }
877 
878         pszTempBuf = Alloc( (convertToUnicode ? sizeof(WCHAR) : sizeof(CHAR)) * cchTempBufMax);
879         if (!pszTempBuf) return FALSE;
880 
881         if (convertToUnicode)
882             MultiByteToWideChar(CP_ACP, 0, (LPCSTR)pdi->item.pszText, -1,
883                                 pszTempBuf, cchTempBufMax);
884         else
885             WideCharToMultiByte(CP_ACP, 0, pdi->item.pszText, -1, (LPSTR) pszTempBuf,
886                                 cchTempBufMax, NULL, NULL);
887 
888         savCchTextMax = pdi->item.cchTextMax;
889         savPszText = pdi->item.pszText;
890         pdi->item.pszText = pszTempBuf;
891         pdi->item.cchTextMax = cchTempBufMax;
892     }
893 
894     if (infoPtr->notifyFormat == NFR_ANSI)
895         realNotifCode = get_ansi_notification(notificationCode);
896     else
897         realNotifCode = notificationCode;
898     TRACE(" pdi->item=%s\n", debuglvitem_t(&pdi->item, infoPtr->notifyFormat != NFR_ANSI));
899     bResult = notify_hdr(infoPtr, realNotifCode, &pdi->hdr);
900 
901     if (convertToUnicode || convertToAnsi)
902     {
903         if (convertToUnicode) /* note : pointer can be changed by app ! */
904             WideCharToMultiByte(CP_ACP, 0, pdi->item.pszText, -1, (LPSTR) savPszText,
905                                 savCchTextMax, NULL, NULL);
906         else
907             MultiByteToWideChar(CP_ACP, 0, (LPSTR) pdi->item.pszText, -1,
908                                 savPszText, savCchTextMax);
909         pdi->item.pszText = savPszText; /* restores our buffer */
910         pdi->item.cchTextMax = savCchTextMax;
911         Free (pszTempBuf);
912     }
913     return bResult;
914 }
915 
916 static void customdraw_fill(NMLVCUSTOMDRAW *lpnmlvcd, const LISTVIEW_INFO *infoPtr, HDC hdc,
917                             const RECT *rcBounds, const LVITEMW *lplvItem)
918 {
919     ZeroMemory(lpnmlvcd, sizeof(NMLVCUSTOMDRAW));
920     lpnmlvcd->nmcd.hdc = hdc;
921     lpnmlvcd->nmcd.rc = *rcBounds;
922     lpnmlvcd->clrTextBk = infoPtr->clrTextBk;
923     lpnmlvcd->clrText   = infoPtr->clrText;
924     if (!lplvItem) return;
925     lpnmlvcd->nmcd.dwItemSpec = lplvItem->iItem + 1;
926     lpnmlvcd->iSubItem = lplvItem->iSubItem;
927     if (lplvItem->state & LVIS_SELECTED) lpnmlvcd->nmcd.uItemState |= CDIS_SELECTED;
928     if (lplvItem->state & LVIS_FOCUSED) lpnmlvcd->nmcd.uItemState |= CDIS_FOCUS;
929     if (lplvItem->iItem == infoPtr->nHotItem) lpnmlvcd->nmcd.uItemState |= CDIS_HOT;
930     lpnmlvcd->nmcd.lItemlParam = lplvItem->lParam;
931 }
932 
933 static inline DWORD notify_customdraw (const LISTVIEW_INFO *infoPtr, DWORD dwDrawStage, NMLVCUSTOMDRAW *lpnmlvcd)
934 {
935     BOOL isForItem = (lpnmlvcd->nmcd.dwItemSpec != 0);
936     DWORD result;
937 
938     lpnmlvcd->nmcd.dwDrawStage = dwDrawStage;
939     if (isForItem) lpnmlvcd->nmcd.dwDrawStage |= CDDS_ITEM; 
940     if (lpnmlvcd->iSubItem) lpnmlvcd->nmcd.dwDrawStage |= CDDS_SUBITEM;
941     if (isForItem) lpnmlvcd->nmcd.dwItemSpec--;
942     result = notify_hdr(infoPtr, NM_CUSTOMDRAW, &lpnmlvcd->nmcd.hdr);
943     if (isForItem) lpnmlvcd->nmcd.dwItemSpec++;
944     return result;
945 }
946 
947 static void prepaint_setup (const LISTVIEW_INFO *infoPtr, HDC hdc, NMLVCUSTOMDRAW *lpnmlvcd, BOOL SubItem)
948 {
949     if (lpnmlvcd->clrTextBk == CLR_DEFAULT)
950         lpnmlvcd->clrTextBk = comctl32_color.clrWindow;
951     if (lpnmlvcd->clrText == CLR_DEFAULT)
952         lpnmlvcd->clrText = comctl32_color.clrWindowText;
953 
954     /* apparently, for selected items, we have to override the returned values */
955     if (!SubItem)
956     {
957         if (lpnmlvcd->nmcd.uItemState & CDIS_SELECTED)
958         {
959             if (infoPtr->bFocus)
960             {
961                 lpnmlvcd->clrTextBk = comctl32_color.clrHighlight;
962                 lpnmlvcd->clrText   = comctl32_color.clrHighlightText;
963             }
964             else if (infoPtr->dwStyle & LVS_SHOWSELALWAYS)
965             {
966                 lpnmlvcd->clrTextBk = comctl32_color.clr3dFace;
967                 lpnmlvcd->clrText   = comctl32_color.clrBtnText;
968             }
969         }
970     }
971 
972     /* Set the text attributes */
973     if (lpnmlvcd->clrTextBk != CLR_NONE)
974     {
975         SetBkMode(hdc, OPAQUE);
976         SetBkColor(hdc,lpnmlvcd->clrTextBk);
977     }
978     else
979         SetBkMode(hdc, TRANSPARENT);
980     SetTextColor(hdc, lpnmlvcd->clrText);
981 }
982 
983 static inline DWORD notify_postpaint (const LISTVIEW_INFO *infoPtr, NMLVCUSTOMDRAW *lpnmlvcd)
984 {
985     return notify_customdraw(infoPtr, CDDS_POSTPAINT, lpnmlvcd);
986 }
987 
988 /******** Item iterator functions **********************************/
989 
990 static RANGES ranges_create(int count);
991 static void ranges_destroy(RANGES ranges);
992 static BOOL ranges_add(RANGES ranges, RANGE range);
993 static BOOL ranges_del(RANGES ranges, RANGE range);
994 static void ranges_dump(RANGES ranges);
995 
996 static inline BOOL ranges_additem(RANGES ranges, INT nItem)
997 {
998     RANGE range = { nItem, nItem + 1 };
999 
1000     return ranges_add(ranges, range);
1001 }
1002 
1003 static inline BOOL ranges_delitem(RANGES ranges, INT nItem)
1004 {
1005     RANGE range = { nItem, nItem + 1 };
1006 
1007     return ranges_del(ranges, range);
1008 }
1009 
1010 /***
1011  * ITERATOR DOCUMENTATION
1012  *
1013  * The iterator functions allow for easy, and convenient iteration
1014  * over items of interest in the list. Typically, you create a
1015  * iterator, use it, and destroy it, as such:
1016  *   ITERATOR i;
1017  *
1018  *   iterator_xxxitems(&i, ...);
1019  *   while (iterator_{prev,next}(&i)
1020  *   {
1021  *       //code which uses i.nItem
1022  *   }
1023  *   iterator_destroy(&i);
1024  *
1025  *   where xxx is either: framed, or visible.
1026  * Note that it is important that the code destroys the iterator
1027  * after it's done with it, as the creation of the iterator may
1028  * allocate memory, which thus needs to be freed.
1029  * 
1030  * You can iterate both forwards, and backwards through the list,
1031  * by using iterator_next or iterator_prev respectively.
1032  * 
1033  * Lower numbered items are draw on top of higher number items in
1034  * LVS_ICON, and LVS_SMALLICON (which are the only modes where
1035  * items may overlap). So, to test items, you should use
1036  *    iterator_next
1037  * which lists the items top to bottom (in Z-order).
1038  * For drawing items, you should use
1039  *    iterator_prev
1040  * which lists the items bottom to top (in Z-order).
1041  * If you keep iterating over the items after the end-of-items
1042  * marker (-1) is returned, the iterator will start from the
1043  * beginning. Typically, you don't need to test for -1,
1044  * because iterator_{next,prev} will return TRUE if more items
1045  * are to be iterated over, or FALSE otherwise.
1046  *
1047  * Note: the iterator is defined to be bidirectional. That is,
1048  *       any number of prev followed by any number of next, or
1049  *       five versa, should leave the iterator at the same item:
1050  *           prev * n, next * n = next * n, prev * n
1051  *
1052  * The iterator has a notion of an out-of-order, special item,
1053  * which sits at the start of the list. This is used in
1054  * LVS_ICON, and LVS_SMALLICON mode to handle the focused item,
1055  * which needs to be first, as it may overlap other items.
1056  *           
1057  * The code is a bit messy because we have:
1058  *   - a special item to deal with
1059  *   - simple range, or composite range
1060  *   - empty range.
1061  * If you find bugs, or want to add features, please make sure you
1062  * always check/modify *both* iterator_prev, and iterator_next.
1063  */
1064 
1065 /****
1066  * This function iterates through the items in increasing order,
1067  * but prefixed by the special item, then -1. That is:
1068  *    special, 1, 2, 3, ..., n, -1.
1069  * Each item is listed only once.
1070  */
1071 static inline BOOL iterator_next(ITERATOR* i)
1072 {
1073     if (i->nItem == -1)
1074     {
1075         i->nItem = i->nSpecial;
1076         if (i->nItem != -1) return TRUE;
1077     }
1078     if (i->nItem == i->nSpecial)
1079     {
1080         if (i->ranges) i->index = 0;
1081         goto pickarange;
1082     }
1083 
1084     i->nItem++;
1085 testitem:
1086     if (i->nItem == i->nSpecial) i->nItem++;
1087     if (i->nItem < i->range.upper) return TRUE;
1088 
1089 pickarange:
1090     if (i->ranges)
1091     {
1092         if (i->index < DPA_GetPtrCount(i->ranges->hdpa))
1093             i->range = *(RANGE*)DPA_GetPtr(i->ranges->hdpa, i->index++);
1094         else goto end;
1095     }
1096     else if (i->nItem >= i->range.upper) goto end;
1097 
1098     i->nItem = i->range.lower;
1099     if (i->nItem >= 0) goto testitem;
1100 end:
1101     i->nItem = -1;
1102     return FALSE;
1103 }
1104 
1105 /****
1106  * This function iterates through the items in decreasing order,
1107  * followed by the special item, then -1. That is:
1108  *    n, n-1, ..., 3, 2, 1, special, -1.
1109  * Each item is listed only once.
1110  */
1111 static inline BOOL iterator_prev(ITERATOR* i)
1112 {
1113     BOOL start = FALSE;
1114 
1115     if (i->nItem == -1)
1116     {
1117         start = TRUE;
1118         if (i->ranges) i->index = DPA_GetPtrCount(i->ranges->hdpa);
1119         goto pickarange;
1120     }
1121     if (i->nItem == i->nSpecial)
1122     {
1123         i->nItem = -1;
1124         return FALSE;
1125     }
1126 
1127 testitem:
1128     i->nItem--;
1129     if (i->nItem == i->nSpecial) i->nItem--;
1130     if (i->nItem >= i->range.lower) return TRUE;
1131 
1132 pickarange:
1133     if (i->ranges)
1134     {
1135         if (i->index > 0)
1136             i->range = *(RANGE*)DPA_GetPtr(i->ranges->hdpa, --i->index);
1137         else goto end;
1138     }
1139     else if (!start && i->nItem < i->range.lower) goto end;
1140 
1141     i->nItem = i->range.upper;
1142     if (i->nItem > 0) goto testitem;
1143 end:
1144     return (i->nItem = i->nSpecial) != -1;
1145 }
1146 
1147 static RANGE iterator_range(const ITERATOR *i)
1148 {
1149     RANGE range;
1150 
1151     if (!i->ranges) return i->range;
1152 
1153     if (DPA_GetPtrCount(i->ranges->hdpa) > 0)
1154     {
1155         range.lower = (*(RANGE*)DPA_GetPtr(i->ranges->hdpa, 0)).lower;
1156         range.upper = (*(RANGE*)DPA_GetPtr(i->ranges->hdpa, DPA_GetPtrCount(i->ranges->hdpa) - 1)).upper;
1157     }
1158     else range.lower = range.upper = 0;
1159 
1160     return range;
1161 }
1162 
1163 /***
1164  * Releases resources associated with this ierator.
1165  */
1166 static inline void iterator_destroy(const ITERATOR *i)
1167 {
1168     ranges_destroy(i->ranges);
1169 }
1170 
1171 /***
1172  * Create an empty iterator.
1173  */
1174 static inline BOOL iterator_empty(ITERATOR* i)
1175 {
1176     ZeroMemory(i, sizeof(*i));
1177     i->nItem = i->nSpecial = i->range.lower = i->range.upper = -1;
1178     return TRUE;
1179 }
1180 
1181 /***
1182  * Create an iterator over a range.
1183  */
1184 static inline BOOL iterator_rangeitems(ITERATOR* i, RANGE range)
1185 {
1186     iterator_empty(i);
1187     i->range = range;
1188     return TRUE;
1189 }
1190 
1191 /***
1192  * Create an iterator over a bunch of ranges.
1193  * Please note that the iterator will take ownership of the ranges,
1194  * and will free them upon destruction.
1195  */
1196 static inline BOOL iterator_rangesitems(ITERATOR* i, RANGES ranges)
1197 {
1198     iterator_empty(i);
1199     i->ranges = ranges;
1200     return TRUE;
1201 }
1202 
1203 /***
1204  * Creates an iterator over the items which intersect lprc.
1205  */
1206 static BOOL iterator_frameditems(ITERATOR* i, const LISTVIEW_INFO* infoPtr, const RECT *lprc)
1207 {
1208     UINT uView = infoPtr->dwStyle & LVS_TYPEMASK;
1209     RECT frame = *lprc, rcItem, rcTemp;
1210     POINT Origin;
1211     
1212     /* in case we fail, we want to return an empty iterator */
1213     if (!iterator_empty(i)) return FALSE;
1214 
1215     LISTVIEW_GetOrigin(infoPtr, &Origin);
1216 
1217     TRACE("(lprc=%s)\n", wine_dbgstr_rect(lprc));
1218     OffsetRect(&frame, -Origin.x, -Origin.y);
1219 
1220     if (uView == LVS_ICON || uView == LVS_SMALLICON)
1221     {
1222         INT nItem;
1223         
1224         if (uView == LVS_ICON && infoPtr->nFocusedItem != -1)
1225         {
1226             LISTVIEW_GetItemBox(infoPtr, infoPtr->nFocusedItem, &rcItem);
1227             if (IntersectRect(&rcTemp, &rcItem, lprc))
1228                 i->nSpecial = infoPtr->nFocusedItem;
1229         }
1230         if (!(iterator_rangesitems(i, ranges_create(50)))) return FALSE;
1231         /* to do better here, we need to have PosX, and PosY sorted */
1232         TRACE("building icon ranges:\n");
1233         for (nItem = 0; nItem < infoPtr->nItemCount; nItem++)
1234         {
1235             rcItem.left = (LONG_PTR)DPA_GetPtr(infoPtr->hdpaPosX, nItem);
1236             rcItem.top = (LONG_PTR)DPA_GetPtr(infoPtr->hdpaPosY, nItem);
1237             rcItem.right = rcItem.left + infoPtr->nItemWidth;
1238             rcItem.bottom = rcItem.top + infoPtr->nItemHeight;
1239             if (IntersectRect(&rcTemp, &rcItem, &frame))
1240                 ranges_additem(i->ranges, nItem);
1241         }
1242         return TRUE;
1243     }
1244     else if (uView == LVS_REPORT)
1245     {
1246         RANGE range;
1247         
1248         if (frame.left >= infoPtr->nItemWidth) return TRUE;
1249         if (frame.top >= infoPtr->nItemHeight * infoPtr->nItemCount) return TRUE;
1250         
1251         range.lower = max(frame.top / infoPtr->nItemHeight, 0);
1252         range.upper = min((frame.bottom - 1) / infoPtr->nItemHeight, infoPtr->nItemCount - 1) + 1;
1253         if (range.upper <= range.lower) return TRUE;
1254         if (!iterator_rangeitems(i, range)) return FALSE;
1255         TRACE("    report=%s\n", debugrange(&i->range));
1256     }
1257     else
1258     {
1259         INT nPerCol = max((infoPtr->rcList.bottom - infoPtr->rcList.top) / infoPtr->nItemHeight, 1);
1260         INT nFirstRow = max(frame.top / infoPtr->nItemHeight, 0);
1261         INT nLastRow = min((frame.bottom - 1) / infoPtr->nItemHeight, nPerCol - 1);
1262         INT nFirstCol = max(frame.left / infoPtr->nItemWidth, 0);
1263         INT nLastCol = min((frame.right - 1) / infoPtr->nItemWidth, (infoPtr->nItemCount + nPerCol - 1) / nPerCol);
1264         INT lower = nFirstCol * nPerCol + nFirstRow;
1265         RANGE item_range;
1266         INT nCol;
1267 
1268         TRACE("nPerCol=%d, nFirstRow=%d, nLastRow=%d, nFirstCol=%d, nLastCol=%d, lower=%d\n",
1269               nPerCol, nFirstRow, nLastRow, nFirstCol, nLastCol, lower);
1270         
1271         if (nLastCol < nFirstCol || nLastRow < nFirstRow) return TRUE;
1272 
1273         if (!(iterator_rangesitems(i, ranges_create(nLastCol - nFirstCol + 1)))) return FALSE;
1274         TRACE("building list ranges:\n");
1275         for (nCol = nFirstCol; nCol <= nLastCol; nCol++)
1276         {
1277             item_range.lower = nCol * nPerCol + nFirstRow;
1278             if(item_range.lower >= infoPtr->nItemCount) break;
1279             item_range.upper = min(nCol * nPerCol + nLastRow + 1, infoPtr->nItemCount);
1280             TRACE("   list=%s\n", debugrange(&item_range));
1281             ranges_add(i->ranges, item_range);
1282         }
1283     }
1284 
1285     return TRUE;
1286 }
1287 
1288 /***
1289  * Creates an iterator over the items which intersect the visible region of hdc.
1290  */
1291 static BOOL iterator_visibleitems(ITERATOR *i, const LISTVIEW_INFO *infoPtr, HDC  hdc)
1292 {
1293     POINT Origin, Position;
1294     RECT rcItem, rcClip;
1295     INT rgntype;
1296     
1297     rgntype = GetClipBox(hdc, &rcClip);
1298     if (rgntype == NULLREGION) return iterator_empty(i);
1299     if (!iterator_frameditems(i, infoPtr, &rcClip)) return FALSE;
1300     if (rgntype == SIMPLEREGION) return TRUE;
1301 
1302     /* first deal with the special item */
1303     if (i->nSpecial != -1)
1304     {
1305         LISTVIEW_GetItemBox(infoPtr, i->nSpecial, &rcItem);
1306         if (!RectVisible(hdc, &rcItem)) i->nSpecial = -1;
1307     }
1308     
1309     /* if we can't deal with the region, we'll just go with the simple range */
1310     LISTVIEW_GetOrigin(infoPtr, &Origin);
1311     TRACE("building visible range:\n");
1312     if (!i->ranges && i->range.lower < i->range.upper)
1313     {
1314         if (!(i->ranges = ranges_create(50))) return TRUE;
1315         if (!ranges_add(i->ranges, i->range))
1316         {
1317             ranges_destroy(i->ranges);
1318             i->ranges = 0;
1319             return TRUE;
1320         }
1321     }
1322 
1323     /* now delete the invisible items from the list */
1324     while(iterator_next(i))
1325     {
1326         LISTVIEW_GetItemOrigin(infoPtr, i->nItem, &Position);
1327         rcItem.left = Position.x + Origin.x;
1328         rcItem.top = Position.y + Origin.y;
1329         rcItem.right = rcItem.left + infoPtr->nItemWidth;
1330         rcItem.bottom = rcItem.top + infoPtr->nItemHeight;
1331         if (!RectVisible(hdc, &rcItem))
1332             ranges_delitem(i->ranges, i->nItem);
1333     }
1334     /* the iterator should restart on the next iterator_next */
1335     TRACE("done\n");
1336     
1337     return TRUE;
1338 }
1339 
1340 /******** Misc helper functions ************************************/
1341 
1342 static inline LRESULT CallWindowProcT(WNDPROC proc, HWND hwnd, UINT uMsg,
1343                                       WPARAM wParam, LPARAM lParam, BOOL isW)
1344 {
1345     if (isW) return CallWindowProcW(proc, hwnd, uMsg, wParam, lParam);
1346     else return CallWindowProcA(proc, hwnd, uMsg, wParam, lParam);
1347 }
1348 
1349 static inline BOOL is_autoarrange(const LISTVIEW_INFO *infoPtr)
1350 {
1351     UINT uView = infoPtr->dwStyle & LVS_TYPEMASK;
1352     
1353     return ((infoPtr->dwStyle & LVS_AUTOARRANGE) || infoPtr->bAutoarrange) &&
1354            (uView == LVS_ICON || uView == LVS_SMALLICON);
1355 }
1356 
1357 static void toggle_checkbox_state(LISTVIEW_INFO *infoPtr, INT nItem)
1358 {
1359     DWORD state = STATEIMAGEINDEX(LISTVIEW_GetItemState(infoPtr, nItem, LVIS_STATEIMAGEMASK));
1360     if(state == 1 || state == 2)
1361     {
1362         LVITEMW lvitem;
1363         state ^= 3;
1364         lvitem.state = INDEXTOSTATEIMAGEMASK(state);
1365         lvitem.stateMask = LVIS_STATEIMAGEMASK;
1366         LISTVIEW_SetItemState(infoPtr, nItem, &lvitem);
1367     }
1368 }
1369 
1370 /******** Internal API functions ************************************/
1371 
1372 static inline COLUMN_INFO * LISTVIEW_GetColumnInfo(const LISTVIEW_INFO *infoPtr, INT nSubItem)
1373 {
1374     static COLUMN_INFO mainItem;
1375 
1376     if (nSubItem == 0 && DPA_GetPtrCount(infoPtr->hdpaColumns) == 0) return &mainItem;
1377     assert (nSubItem >= 0 && nSubItem < DPA_GetPtrCount(infoPtr->hdpaColumns));
1378     return (COLUMN_INFO *)DPA_GetPtr(infoPtr->hdpaColumns, nSubItem);
1379 }
1380         
1381 static inline void LISTVIEW_GetHeaderRect(const LISTVIEW_INFO *infoPtr, INT nSubItem, LPRECT lprc)
1382 {
1383     *lprc = LISTVIEW_GetColumnInfo(infoPtr, nSubItem)->rcHeader;
1384 }
1385         
1386 static inline BOOL LISTVIEW_GetItemW(const LISTVIEW_INFO *infoPtr, LPLVITEMW lpLVItem)
1387 {
1388     return LISTVIEW_GetItemT(infoPtr, lpLVItem, TRUE);
1389 }
1390 
1391 /* Listview invalidation functions: use _only_ these functions to invalidate */
1392 
1393 static inline BOOL is_redrawing(const LISTVIEW_INFO *infoPtr)
1394 {
1395     return infoPtr->bRedraw;
1396 }
1397 
1398 static inline void LISTVIEW_InvalidateRect(const LISTVIEW_INFO *infoPtr, const RECT* rect)
1399 {
1400     if(!is_redrawing(infoPtr)) return; 
1401     TRACE(" invalidating rect=%s\n", wine_dbgstr_rect(rect));
1402     InvalidateRect(infoPtr->hwndSelf, rect, TRUE);
1403 }
1404 
1405 static inline void LISTVIEW_InvalidateItem(const LISTVIEW_INFO *infoPtr, INT nItem)
1406 {
1407     RECT rcBox;
1408 
1409     if(!is_redrawing(infoPtr)) return; 
1410     LISTVIEW_GetItemBox(infoPtr, nItem, &rcBox);
1411     LISTVIEW_InvalidateRect(infoPtr, &rcBox);
1412 }
1413 
1414 static inline void LISTVIEW_InvalidateSubItem(const LISTVIEW_INFO *infoPtr, INT nItem, INT nSubItem)
1415 {
1416     POINT Origin, Position;
1417     RECT rcBox;
1418     
1419     if(!is_redrawing(infoPtr)) return; 
1420     assert ((infoPtr->dwStyle & LVS_TYPEMASK) == LVS_REPORT);
1421     LISTVIEW_GetOrigin(infoPtr, &Origin);
1422     LISTVIEW_GetItemOrigin(infoPtr, nItem, &Position);
1423     LISTVIEW_GetHeaderRect(infoPtr, nSubItem, &rcBox);
1424     rcBox.top = 0;
1425     rcBox.bottom = infoPtr->nItemHeight;
1426     OffsetRect(&rcBox, Origin.x + Position.x, Origin.y + Position.y);
1427     LISTVIEW_InvalidateRect(infoPtr, &rcBox);
1428 }
1429 
1430 static inline void LISTVIEW_InvalidateList(const LISTVIEW_INFO *infoPtr)
1431 {
1432     LISTVIEW_InvalidateRect(infoPtr, NULL);
1433 }
1434 
1435 static inline void LISTVIEW_InvalidateColumn(const LISTVIEW_INFO *infoPtr, INT nColumn)
1436 {
1437     RECT rcCol;
1438     
1439     if(!is_redrawing(infoPtr)) return; 
1440     LISTVIEW_GetHeaderRect(infoPtr, nColumn, &rcCol);
1441     rcCol.top = infoPtr->rcList.top;
1442     rcCol.bottom = infoPtr->rcList.bottom;
1443     LISTVIEW_InvalidateRect(infoPtr, &rcCol);
1444 }
1445 
1446 /***
1447  * DESCRIPTION:
1448  * Retrieves the number of items that can fit vertically in the client area.
1449  *
1450  * PARAMETER(S):
1451  * [I] infoPtr : valid pointer to the listview structure
1452  *
1453  * RETURN:
1454  * Number of items per row.
1455  */
1456 static inline INT LISTVIEW_GetCountPerRow(const LISTVIEW_INFO *infoPtr)
1457 {
1458     INT nListWidth = infoPtr->rcList.right - infoPtr->rcList.left;
1459 
1460     return max(nListWidth/infoPtr->nItemWidth, 1);
1461 }
1462 
1463 /***
1464  * DESCRIPTION:
1465  * Retrieves the number of items that can fit horizontally in the client
1466  * area.
1467  *
1468  * PARAMETER(S):
1469  * [I] infoPtr : valid pointer to the listview structure
1470  *
1471  * RETURN:
1472  * Number of items per column.
1473  */
1474 static inline INT LISTVIEW_GetCountPerColumn(const LISTVIEW_INFO *infoPtr)
1475 {
1476     INT nListHeight = infoPtr->rcList.bottom - infoPtr->rcList.top;
1477 
1478     return max(nListHeight / infoPtr->nItemHeight, 1);
1479 }
1480 
1481 
1482 /*************************************************************************
1483  *              LISTVIEW_ProcessLetterKeys
1484  *
1485  *  Processes keyboard messages generated by pressing the letter keys
1486  *  on the keyboard.
1487  *  What this does is perform a case insensitive search from the
1488  *  current position with the following quirks:
1489  *  - If two chars or more are pressed in quick succession we search
1490  *    for the corresponding string (e.g. 'abc').
1491  *  - If there is a delay we wipe away the current search string and
1492  *    restart with just that char.
1493  *  - If the user keeps pressing the same character, whether slowly or
1494  *    fast, so that the search string is entirely composed of this
1495  *    character ('aaaaa' for instance), then we search for first item
1496  *    that starting with that character.
1497  *  - If the user types the above character in quick succession, then
1498  *    we must also search for the corresponding string ('aaaaa'), and
1499  *    go to that string if there is a match.
1500  *
1501  * PARAMETERS
1502  *   [I] hwnd : handle to the window
1503  *   [I] charCode : the character code, the actual character
1504  *   [I] keyData : key data
1505  *
1506  * RETURNS
1507  *
1508  *  Zero.
1509  *
1510  * BUGS
1511  *
1512  *  - The current implementation has a list of characters it will
1513  *    accept and it ignores everything else. In particular it will
1514  *    ignore accentuated characters which seems to match what
1515  *    Windows does. But I'm not sure it makes sense to follow
1516  *    Windows there.
1517  *  - We don't sound a beep when the search fails.
1518  *
1519  * SEE ALSO
1520  *
1521  *  TREEVIEW_ProcessLetterKeys
1522  */
1523 static INT LISTVIEW_ProcessLetterKeys(LISTVIEW_INFO *infoPtr, WPARAM charCode, LPARAM keyData)
1524 {
1525     INT nItem;
1526     INT endidx,idx;
1527     LVITEMW item;
1528     WCHAR buffer[MAX_PATH];
1529     DWORD lastKeyPressTimestamp = infoPtr->lastKeyPressTimestamp;
1530 
1531     /* simple parameter checking */
1532     if (!charCode || !keyData) return 0;
1533 
1534     /* only allow the valid WM_CHARs through */
1535     if (!isalnum(charCode) &&
1536         charCode != '.' && charCode != '`' && charCode != '!' &&
1537         charCode != '@' && charCode != '#' && charCode != '$' &&
1538         charCode != '%' && charCode != '^' && charCode != '&' &&
1539         charCode != '*' && charCode != '(' && charCode != ')' &&
1540         charCode != '-' && charCode != '_' && charCode != '+' &&
1541         charCode != '=' && charCode != '\\'&& charCode != ']' &&
1542         charCode != '}' && charCode != '[' && charCode != '{' &&
1543         charCode != '/' && charCode != '?' && charCode != '>' &&
1544         charCode != '<' && charCode != ',' && charCode != '~')
1545         return 0;
1546 
1547     /* if there's one item or less, there is no where to go */
1548     if (infoPtr->nItemCount <= 1) return 0;
1549 
1550     /* update the search parameters */
1551     infoPtr->lastKeyPressTimestamp = GetTickCount();
1552     if (infoPtr->lastKeyPressTimestamp - lastKeyPressTimestamp < KEY_DELAY) {
1553         if (infoPtr->nSearchParamLength < MAX_PATH)
1554             infoPtr->szSearchParam[infoPtr->nSearchParamLength++]=charCode;
1555         if (infoPtr->charCode != charCode)
1556             infoPtr->charCode = charCode = 0;
1557     } else {
1558         infoPtr->charCode=charCode;
1559         infoPtr->szSearchParam[0]=charCode;
1560         infoPtr->nSearchParamLength=1;
1561         /* Redundant with the 1 char string */
1562         charCode=0;
1563     }
1564 
1565     /* and search from the current position */
1566     nItem=-1;
1567     if (infoPtr->nFocusedItem >= 0) {
1568         endidx=infoPtr->nFocusedItem;
1569         idx=endidx;
1570         /* if looking for single character match,
1571          * then we must always move forward
1572          */
1573         if (infoPtr->nSearchParamLength == 1)
1574             idx++;
1575     } else {
1576         endidx=infoPtr->nItemCount;
1577         idx=0;
1578     }
1579     do {
1580         if (idx == infoPtr->nItemCount) {
1581             if (endidx == infoPtr->nItemCount || endidx == 0)
1582                 break;
1583             idx=0;
1584         }
1585 
1586         /* get item */
1587         item.mask = LVIF_TEXT;
1588         item.iItem = idx;
1589         item.iSubItem = 0;
1590         item.pszText = buffer;
1591         item.cchTextMax = MAX_PATH;
1592         if (!LISTVIEW_GetItemW(infoPtr, &item)) return 0;
1593 
1594         /* check for a match */
1595         if (lstrncmpiW(item.pszText,infoPtr->szSearchParam,infoPtr->nSearchParamLength) == 0) {
1596             nItem=idx;
1597             break;
1598         } else if ( (charCode != 0) && (nItem == -1) && (nItem != infoPtr->nFocusedItem) &&
1599                     (lstrncmpiW(item.pszText,infoPtr->szSearchParam,1) == 0) ) {
1600             /* This would work but we must keep looking for a longer match */
1601             nItem=idx;
1602         }
1603         idx++;
1604     } while (idx != endidx);
1605 
1606     if (nItem != -1)
1607         LISTVIEW_KeySelection(infoPtr, nItem);
1608 
1609     return 0;
1610 }
1611 
1612 /*************************************************************************
1613  * LISTVIEW_UpdateHeaderSize [Internal]
1614  *
1615  * Function to resize the header control
1616  *
1617  * PARAMS
1618  * [I]  hwnd : handle to a window
1619  * [I]  nNewScrollPos : scroll pos to set
1620  *
1621  * RETURNS
1622  * None.
1623  */
1624 static void LISTVIEW_UpdateHeaderSize(const LISTVIEW_INFO *infoPtr, INT nNewScrollPos)
1625 {
1626     RECT winRect;
1627     POINT point[2];
1628 
1629     TRACE("nNewScrollPos=%d\n", nNewScrollPos);
1630 
1631     GetWindowRect(infoPtr->hwndHeader, &winRect);
1632     point[0].x = winRect.left;
1633     point[0].y = winRect.top;
1634     point[1].x = winRect.right;
1635     point[1].y = winRect.bottom;
1636 
1637     MapWindowPoints(HWND_DESKTOP, infoPtr->hwndSelf, point, 2);
1638     point[0].x = -nNewScrollPos;
1639     point[1].x += nNewScrollPos;
1640 
1641     SetWindowPos(infoPtr->hwndHeader,0,
1642         point[0].x,point[0].y,point[1].x,point[1].y,
1643         (infoPtr->dwStyle & LVS_NOCOLUMNHEADER) ? SWP_HIDEWINDOW : SWP_SHOWWINDOW |
1644         SWP_NOZORDER | SWP_NOACTIVATE);
1645 }
1646 
1647 /***
1648  * DESCRIPTION:
1649  * Update the scrollbars. This functions should be called whenever
1650  * the content, size or view changes.
1651  *
1652  * PARAMETER(S):
1653  * [I] infoPtr : valid pointer to the listview structure
1654  *
1655  * RETURN:
1656  * None
1657  */
1658 static void LISTVIEW_UpdateScroll(const LISTVIEW_INFO *infoPtr)
1659 {
1660     UINT uView = infoPtr->dwStyle & LVS_TYPEMASK;
1661     SCROLLINFO horzInfo, vertInfo;
1662     INT dx, dy;
1663 
1664     if ((infoPtr->dwStyle & LVS_NOSCROLL) || !is_redrawing(infoPtr)) return;
1665 
1666     ZeroMemory(&horzInfo, sizeof(SCROLLINFO));
1667     horzInfo.cbSize = sizeof(SCROLLINFO);
1668     horzInfo.nPage = infoPtr->rcList.right - infoPtr->rcList.left;
1669 
1670     /* for now, we'll set info.nMax to the _count_, and adjust it later */
1671     if (uView == LVS_LIST)
1672     {
1673         INT nPerCol = LISTVIEW_GetCountPerColumn(infoPtr);
1674         horzInfo.nMax = (infoPtr->nItemCount + nPerCol - 1) / nPerCol;
1675 
1676         /* scroll by at least one column per page */
1677         if(horzInfo.nPage < infoPtr->nItemWidth)
1678                 horzInfo.nPage = infoPtr->nItemWidth;
1679 
1680         horzInfo.nPage /= infoPtr->nItemWidth;
1681     }
1682     else if (uView == LVS_REPORT)
1683     {
1684         horzInfo.nMax = infoPtr->nItemWidth;
1685     }
1686     else /* LVS_ICON, or LVS_SMALLICON */
1687     {
1688         RECT rcView;
1689 
1690         if (LISTVIEW_GetViewRect(infoPtr, &rcView)) horzInfo.nMax = rcView.right - rcView.left;
1691     }
1692   
1693     horzInfo.fMask = SIF_RANGE | SIF_PAGE;
1694     horzInfo.nMax = max(horzInfo.nMax - 1, 0);
1695     dx = GetScrollPos(infoPtr->hwndSelf, SB_HORZ);
1696     dx -= SetScrollInfo(infoPtr->hwndSelf, SB_HORZ, &horzInfo, TRUE);
1697     TRACE("horzInfo=%s\n", debugscrollinfo(&horzInfo));
1698 
1699     /* Setting the horizontal scroll can change the listview size
1700      * (and potentially everything else) so we need to recompute
1701      * everything again for the vertical scroll
1702      */
1703 
1704     ZeroMemory(&vertInfo, sizeof(SCROLLINFO));
1705     vertInfo.cbSize = sizeof(SCROLLINFO);
1706     vertInfo.nPage = infoPtr->rcList.bottom - infoPtr->rcList.top;
1707 
1708     if (uView == LVS_REPORT)
1709     {
1710         vertInfo.nMax = infoPtr->nItemCount;
1711         
1712         /* scroll by at least one page */
1713         if(vertInfo.nPage < infoPtr->nItemHeight)
1714           vertInfo.nPage = infoPtr->nItemHeight;
1715 
1716         vertInfo.nPage /= infoPtr->nItemHeight;
1717     }
1718     else if (uView != LVS_LIST) /* LVS_ICON, or LVS_SMALLICON */
1719     {
1720         RECT rcView;
1721 
1722         if (LISTVIEW_GetViewRect(infoPtr, &rcView)) vertInfo.nMax = rcView.bottom - rcView.top;
1723     }
1724 
1725     vertInfo.fMask = SIF_RANGE | SIF_PAGE;
1726     vertInfo.nMax = max(vertInfo.nMax - 1, 0);
1727     dy = GetScrollPos(infoPtr->hwndSelf, SB_VERT);
1728     dy -= SetScrollInfo(infoPtr->hwndSelf, SB_VERT, &vertInfo, TRUE);
1729     TRACE("vertInfo=%s\n", debugscrollinfo(&vertInfo));
1730 
1731     /* Change of the range may have changed the scroll pos. If so move the content */
1732     if (dx != 0 || dy != 0)
1733     {
1734         RECT listRect;
1735         listRect = infoPtr->rcList;
1736         ScrollWindowEx(infoPtr->hwndSelf, dx, dy, &listRect, &listRect, 0, 0,
1737             SW_ERASE | SW_INVALIDATE);
1738     }
1739 
1740     /* Update the Header Control */
1741     if (uView == LVS_REPORT)
1742     {
1743         horzInfo.fMask = SIF_POS;
1744         GetScrollInfo(infoPtr->hwndSelf, SB_HORZ, &horzInfo);
1745         LISTVIEW_UpdateHeaderSize(infoPtr, horzInfo.nPos);
1746     }
1747 }
1748 
1749 
1750 /***
1751  * DESCRIPTION:
1752  * Shows/hides the focus rectangle. 
1753  *
1754  * PARAMETER(S):
1755  * [I] infoPtr : valid pointer to the listview structure
1756  * [I] fShow : TRUE to show the focus, FALSE to hide it.
1757  *
1758  * RETURN:
1759  * None
1760  */
1761 static void LISTVIEW_ShowFocusRect(const LISTVIEW_INFO *infoPtr, BOOL fShow)
1762 {
1763     UINT uView = infoPtr->dwStyle & LVS_TYPEMASK;
1764     HDC hdc;
1765 
1766     TRACE("fShow=%d, nItem=%d\n", fShow, infoPtr->nFocusedItem);
1767 
1768     if (infoPtr->nFocusedItem < 0) return;
1769 
1770     /* we need some gymnastics in ICON mode to handle large items */
1771     if ( (infoPtr->dwStyle & LVS_TYPEMASK) == LVS_ICON )
1772     {
1773         RECT rcBox;
1774 
1775         LISTVIEW_GetItemBox(infoPtr, infoPtr->nFocusedItem, &rcBox); 
1776         if ((rcBox.bottom - rcBox.top) > infoPtr->nItemHeight)
1777         {
1778             LISTVIEW_InvalidateRect(infoPtr, &rcBox);
1779             return;
1780         }
1781     }
1782 
1783     if (!(hdc = GetDC(infoPtr->hwndSelf))) return;
1784 
1785     /* for some reason, owner draw should work only in report mode */
1786     if ((infoPtr->dwStyle & LVS_OWNERDRAWFIXED) && (uView == LVS_REPORT))
1787     {
1788         DRAWITEMSTRUCT dis;
1789         LVITEMW item;
1790 
1791         HFONT hFont = infoPtr->hFont ? infoPtr->hFont : infoPtr->hDefaultFont;
1792         HFONT hOldFont = SelectObject(hdc, hFont);
1793 
1794         item.iItem = infoPtr->nFocusedItem;
1795         item.iSubItem = 0;
1796         item.mask = LVIF_PARAM;
1797         if (!LISTVIEW_GetItemW(infoPtr, &item)) goto done;
1798            
1799         ZeroMemory(&dis, sizeof(dis)); 
1800         dis.CtlType = ODT_LISTVIEW;
1801         dis.CtlID = (UINT)GetWindowLongPtrW(infoPtr->hwndSelf, GWLP_ID);
1802         dis.itemID = item.iItem;
1803         dis.itemAction = ODA_FOCUS;
1804         if (fShow) dis.itemState |= ODS_FOCUS;
1805         dis.hwndItem = infoPtr->hwndSelf;
1806         dis.hDC = hdc;
1807         LISTVIEW_GetItemBox(infoPtr, dis.itemID, &dis.rcItem);
1808         dis.itemData = item.lParam;
1809 
1810         SendMessageW(infoPtr->hwndNotify, WM_DRAWITEM, dis.CtlID, (LPARAM)&dis);
1811 
1812         SelectObject(hdc, hOldFont);
1813     }
1814     else
1815     {
1816         DrawFocusRect(hdc, &infoPtr->rcFocus);
1817     }
1818 done:
1819     ReleaseDC(infoPtr->hwndSelf, hdc);
1820 }
1821 
1822 /***
1823  * Invalidates all visible selected items.
1824  */
1825 static void LISTVIEW_InvalidateSelectedItems(const LISTVIEW_INFO *infoPtr)
1826 {
1827     ITERATOR i; 
1828    
1829     iterator_frameditems(&i, infoPtr, &infoPtr->rcList); 
1830     while(iterator_next(&i))
1831     {
1832         if (LISTVIEW_GetItemState(infoPtr, i.nItem, LVIS_SELECTED))
1833             LISTVIEW_InvalidateItem(infoPtr, i.nItem);
1834     }
1835     iterator_destroy(&i);
1836 }
1837 
1838             
1839 /***
1840  * DESCRIPTION:            [INTERNAL]
1841  * Computes an item's (left,top) corner, relative to rcView.
1842  * That is, the position has NOT been made relative to the Origin.
1843  * This is deliberate, to avoid computing the Origin over, and
1844  * over again, when this function is called in a loop. Instead,
1845  * one can factor the computation of the Origin before the loop,
1846  * and offset the value returned by this function, on every iteration.
1847  * 
1848  * PARAMETER(S):
1849  * [I] infoPtr : valid pointer to the listview structure
1850  * [I] nItem  : item number
1851  * [O] lpptOrig : item top, left corner
1852  *
1853  * RETURN:
1854  *   None.
1855  */
1856 static void LISTVIEW_GetItemOrigin(const LISTVIEW_INFO *infoPtr, INT nItem, LPPOINT lpptPosition)
1857 {
1858     UINT uView = infoPtr->dwStyle & LVS_TYPEMASK;
1859 
1860     assert(nItem >= 0 && nItem < infoPtr->nItemCount);
1861 
1862     if ((uView == LVS_SMALLICON) || (uView == LVS_ICON))
1863     {
1864         lpptPosition->x = (LONG_PTR)DPA_GetPtr(infoPtr->hdpaPosX, nItem);
1865         lpptPosition->y = (LONG_PTR)DPA_GetPtr(infoPtr->hdpaPosY, nItem);
1866     }
1867     else if (uView == LVS_LIST)
1868     {
1869         INT nCountPerColumn = LISTVIEW_GetCountPerColumn(infoPtr);
1870         lpptPosition->x = nItem / nCountPerColumn * infoPtr->nItemWidth;
1871         lpptPosition->y = nItem % nCountPerColumn * infoPtr->nItemHeight;
1872     }
1873     else /* LVS_REPORT */
1874     {
1875         lpptPosition->x = 0;
1876         lpptPosition->y = nItem * infoPtr->nItemHeight;
1877     }
1878 }
1879     
1880 /***
1881  * DESCRIPTION:            [INTERNAL]
1882  * Compute the rectangles of an item.  This is to localize all
1883  * the computations in one place. If you are not interested in some
1884  * of these values, simply pass in a NULL -- the function is smart
1885  * enough to compute only what's necessary. The function computes
1886  * the standard rectangles (BOUNDS, ICON, LABEL) plus a non-standard
1887  * one, the BOX rectangle. This rectangle is very cheap to compute,
1888  * and is guaranteed to contain all the other rectangles. Computing
1889  * the ICON rect is also cheap, but all the others are potentially
1890  * expensive. This gives an easy and effective optimization when
1891  * searching (like point inclusion, or rectangle intersection):
1892  * first test against the BOX, and if TRUE, test against the desired
1893  * rectangle.
1894  * If the function does not have all the necessary information
1895  * to computed the requested rectangles, will crash with a
1896  * failed assertion. This is done so we catch all programming
1897  * errors, given that the function is called only from our code.
1898  *
1899  * We have the following 'special' meanings for a few fields:
1900  *   * If LVIS_FOCUSED is set, we assume the item has the focus
1901  *     This is important in ICON mode, where it might get a larger
1902  *     then usual rectangle
1903  *
1904  * Please note that subitem support works only in REPORT mode.
1905  *
1906  * PARAMETER(S):
1907  * [I] infoPtr : valid pointer to the listview structure
1908  * [I] lpLVItem : item to compute the measures for
1909  * [O] lprcBox : ptr to Box rectangle
1910  *                Same as LVM_GETITEMRECT with LVIR_BOUNDS
1911  * [0] lprcSelectBox : ptr to select box rectangle
1912  *                Same as LVM_GETITEMRECT with LVIR_SELECTEDBOUNDS
1913  * [O] lprcIcon : ptr to Icon rectangle
1914  *                Same as LVM_GETITEMRECT with LVIR_ICON
1915  * [O] lprcStateIcon: ptr to State Icon rectangle
1916  * [O] lprcLabel : ptr to Label rectangle
1917  *                Same as LVM_GETITEMRECT with LVIR_LABEL
1918  *
1919  * RETURN:
1920  *   None.
1921  */
1922 static void LISTVIEW_GetItemMetrics(const LISTVIEW_INFO *infoPtr, const LVITEMW *lpLVItem,
1923                                     LPRECT lprcBox, LPRECT lprcSelectBox,
1924                                     LPRECT lprcIcon, LPRECT lprcStateIcon, LPRECT lprcLabel)
1925 {
1926     UINT uView = infoPtr->dwStyle & LVS_TYPEMASK;
1927     BOOL doSelectBox = FALSE, doIcon = FALSE, doLabel = FALSE, oversizedBox = FALSE;
1928     RECT Box, SelectBox, Icon, Label;
1929     COLUMN_INFO *lpColumnInfo = NULL;
1930     SIZE labelSize = { 0, 0 };
1931 
1932     TRACE("(lpLVItem=%s)\n", debuglvitem_t(lpLVItem, TRUE));
1933 
1934     /* Be smart and try to figure out the minimum we have to do */
1935     if (lpLVItem->iSubItem) assert(uView == LVS_REPORT);
1936     if (uView == LVS_ICON && (lprcBox || lprcLabel))
1937     {
1938         assert((lpLVItem->mask & LVIF_STATE) && (lpLVItem->stateMask & LVIS_FOCUSED));
1939         if (lpLVItem->state & LVIS_FOCUSED) oversizedBox = doLabel = TRUE;
1940     }
1941     if (lprcSelectBox) doSelectBox = TRUE;
1942     if (lprcLabel) doLabel = TRUE;
1943     if (doLabel || lprcIcon || lprcStateIcon) doIcon = TRUE;
1944     if (doSelectBox)
1945     {
1946         doIcon = TRUE;
1947         doLabel = TRUE;
1948     }
1949 
1950     /************************************************************/
1951     /* compute the box rectangle (it should be cheap to do)     */
1952     /************************************************************/
1953     if (lpLVItem->iSubItem || uView == LVS_REPORT)
1954         lpColumnInfo = LISTVIEW_GetColumnInfo(infoPtr, lpLVItem->iSubItem);
1955 
1956     if (lpLVItem->iSubItem)    
1957     {
1958         Box = lpColumnInfo->rcHeader;
1959     }
1960     else
1961     {
1962         Box.left = 0;
1963         Box.right = infoPtr->nItemWidth;
1964     }
1965     Box.top = 0;
1966     Box.bottom = infoPtr->nItemHeight;
1967 
1968     /******************************************************************/
1969     /* compute ICON bounding box (ala LVM_GETITEMRECT) and STATEICON  */
1970     /******************************************************************/
1971     if (doIcon)
1972     {
1973         LONG state_width = 0;
1974 
1975         if (infoPtr->himlState && lpLVItem->iSubItem == 0)
1976             state_width = infoPtr->iconStateSize.cx;
1977 
1978         if (uView == LVS_ICON)
1979         {
1980             Icon.left   = Box.left + state_width;
1981             if (infoPtr->himlNormal)
1982                 Icon.left += (infoPtr->nItemWidth - infoPtr->iconSize.cx - state_width) / 2;
1983             Icon.top    = Box.top + ICON_TOP_PADDING;
1984             Icon.right  = Icon.left;
1985             Icon.bottom = Icon.top;
1986             if (infoPtr->himlNormal)
1987             {
1988                 Icon.right  += infoPtr->iconSize.cx;
1989                 Icon.bottom += infoPtr->iconSize.cy;
1990             }
1991         }
1992         else /* LVS_SMALLICON, LVS_LIST or LVS_REPORT */
1993         {
1994             Icon.left   = Box.left + state_width;
1995 
1996             if (uView == LVS_REPORT)
1997                 Icon.left += REPORT_MARGINX;
1998 
1999             Icon.top    = Box.top;
2000             Icon.right  = Icon.left;
2001             if (infoPtr->himlSmall &&
2002                 (!lpColumnInfo || lpLVItem->iSubItem == 0 || (lpColumnInfo->fmt & LVCFMT_IMAGE) ||
2003                  ((infoPtr->dwLvExStyle & LVS_EX_SUBITEMIMAGES) && lpLVItem->iImage != I_IMAGECALLBACK)))
2004                 Icon.right += infoPtr->iconSize.cx;
2005             Icon.bottom = Icon.top + infoPtr->iconSize.cy;
2006         }
2007         if(lprcIcon) *lprcIcon = Icon;
2008         TRACE("    - icon=%s\n", wine_dbgstr_rect(&Icon));
2009 
2010         /* TODO: is this correct? */
2011         if (lprcStateIcon)
2012         {
2013             lprcStateIcon->left = Icon.left - state_width;
2014             lprcStateIcon->right = Icon.left;
2015             lprcStateIcon->top = Icon.top;
2016             lprcStateIcon->bottom = lprcStateIcon->top + infoPtr->iconSize.cy;
2017             TRACE("    - state icon=%s\n", wine_dbgstr_rect(lprcStateIcon));
2018         }
2019      }
2020      else Icon.right = 0;
2021 
2022     /************************************************************/
2023     /* compute LABEL bounding box (ala LVM_GETITEMRECT)         */
2024     /************************************************************/
2025     if (doLabel)
2026     {
2027         /* calculate how far to the right can the label stretch */
2028         Label.right = Box.right;
2029         if (uView == LVS_REPORT)
2030         {
2031             if (lpLVItem->iSubItem == 0) Label = lpColumnInfo->rcHeader;
2032         }
2033 
2034         if (lpLVItem->iSubItem || ((infoPtr->dwStyle & LVS_OWNERDRAWFIXED) && uView == LVS_REPORT))
2035         {
2036            labelSize.cx = infoPtr->nItemWidth;
2037            labelSize.cy = infoPtr->nItemHeight;
2038            goto calc_label;
2039         }
2040         
2041         /* we need the text in non owner draw mode */
2042         assert(lpLVItem->mask & LVIF_TEXT);
2043         if (is_textT(lpLVItem->pszText, TRUE))
2044         {
2045             HFONT hFont = infoPtr->hFont ? infoPtr->hFont : infoPtr->hDefaultFont;
2046             HDC hdc = GetDC(infoPtr->hwndSelf);
2047             HFONT hOldFont = SelectObject(hdc, hFont);
2048             UINT uFormat;
2049             RECT rcText;
2050 
2051             /* compute rough rectangle where the label will go */
2052             SetRectEmpty(&rcText);
2053             rcText.right = infoPtr->nItemWidth - TRAILING_LABEL_PADDING;
2054             rcText.bottom = infoPtr->nItemHeight;
2055             if (uView == LVS_ICON) 
2056                 rcText.bottom -= ICON_TOP_PADDING + infoPtr->iconSize.cy + ICON_BOTTOM_PADDING;
2057 
2058             /* now figure out the flags */
2059             if (uView == LVS_ICON)
2060                 uFormat = oversizedBox ? LV_FL_DT_FLAGS : LV_ML_DT_FLAGS;
2061             else
2062                 uFormat = LV_SL_DT_FLAGS;
2063             
2064             DrawTextW (hdc, lpLVItem->pszText, -1, &rcText, uFormat | DT_CALCRECT);
2065 
2066             labelSize.cx = min(rcText.right - rcText.left + TRAILING_LABEL_PADDING, infoPtr->nItemWidth);
2067             labelSize.cy = rcText.bottom - rcText.top;
2068 
2069             SelectObject(hdc, hOldFont);
2070             ReleaseDC(infoPtr->hwndSelf, hdc);
2071         }
2072 
2073 calc_label:
2074         if (uView == LVS_ICON)
2075         {
2076             Label.left = Box.left + (infoPtr->nItemWidth - labelSize.cx) / 2;
2077             Label.top  = Box.top + ICON_TOP_PADDING_HITABLE +
2078                          infoPtr->iconSize.cy + ICON_BOTTOM_PADDING;
2079             Label.right = Label.left + labelSize.cx;
2080             Label.bottom = Label.top + infoPtr->nItemHeight;
2081             if (!oversizedBox && labelSize.cy > infoPtr->ntmHeight)
2082             {
2083                 labelSize.cy = min(Box.bottom - Label.top, labelSize.cy);
2084                 labelSize.cy /= infoPtr->ntmHeight;
2085                 labelSize.cy = max(labelSize.cy, 1);
2086                 labelSize.cy *= infoPtr->ntmHeight;
2087              }
2088              Label.bottom = Label.top + labelSize.cy + HEIGHT_PADDING;
2089         }
2090         else if (uView == LVS_REPORT)
2091         {
2092             Label.left = Icon.right;
2093             Label.top = Box.top;
2094             Label.right = lpColumnInfo->rcHeader.right;
2095             Label.bottom = Label.top + infoPtr->nItemHeight;
2096         }
2097         else /* LVS_SMALLICON, LVS_LIST or LVS_REPORT */
2098         {
2099             Label.left = Icon.right;
2100             Label.top = Box.top;
2101             Label.right = min(Label.left + labelSize.cx, Label.right);
2102             Label.bottom = Label.top + infoPtr->nItemHeight;
2103         }
2104   
2105         if (lprcLabel) *lprcLabel = Label;
2106         TRACE("    - label=%s\n", wine_dbgstr_rect(&Label));
2107     }
2108 
2109     /************************************************************/
2110     /* compute STATEICON bounding box                           */
2111     /************************************************************/
2112     if (doSelectBox)
2113     {
2114         if (uView == LVS_REPORT)
2115         {
2116             SelectBox.left = Icon.right; /* FIXME: should be Icon.left */
2117             SelectBox.top = Box.top;
2118             SelectBox.bottom = Box.bottom;
2119             if (lpLVItem->iSubItem == 0)
2120             {
2121                 /* we need the indent in report mode */
2122                 assert(lpLVItem->mask & LVIF_INDENT);
2123                 SelectBox.left += infoPtr->iconSize.cx * lpLVItem->iIndent;
2124             }
2125             SelectBox.right = min(SelectBox.left + labelSize.cx, Label.right);
2126         }
2127         else
2128         {
2129             UnionRect(&SelectBox, &Icon, &Label);
2130         }
2131         if (lprcSelectBox) *lprcSelectBox = SelectBox;
2132         TRACE("    - select box=%s\n", wine_dbgstr_rect(&SelectBox));
2133     }
2134 
2135     /* Fix the Box if necessary */
2136     if (lprcBox)
2137     {
2138         if (oversizedBox) UnionRect(lprcBox, &Box, &Label);
2139         else *lprcBox = Box;
2140     }
2141     TRACE("    - box=%s\n", wine_dbgstr_rect(&Box));
2142 }
2143 
2144 /***
2145  * DESCRIPTION:            [INTERNAL]
2146  *
2147  * PARAMETER(S):
2148  * [I] infoPtr : valid pointer to the listview structure
2149  * [I] nItem : item number
2150  * [O] lprcBox : ptr to Box rectangle
2151  *
2152  * RETURN:
2153  *   None.
2154  */
2155 static void LISTVIEW_GetItemBox(const LISTVIEW_INFO *infoPtr, INT nItem, LPRECT lprcBox)
2156 {
2157     UINT uView = infoPtr->dwStyle & LVS_TYPEMASK;
2158     WCHAR szDispText[DISP_TEXT_SIZE] = { '\0' };
2159     POINT Position, Origin;
2160     LVITEMW lvItem;
2161 
2162     LISTVIEW_GetOrigin(infoPtr, &Origin);
2163     LISTVIEW_GetItemOrigin(infoPtr, nItem, &Position);
2164 
2165     /* Be smart and try to figure out the minimum we have to do */
2166     lvItem.mask = 0;
2167     if (uView == LVS_ICON && infoPtr->bFocus && LISTVIEW_GetItemState(infoPtr, nItem, LVIS_FOCUSED))
2168         lvItem.mask |= LVIF_TEXT;
2169     lvItem.iItem = nItem;
2170     lvItem.iSubItem = 0;
2171     lvItem.pszText = szDispText;
2172     lvItem.cchTextMax = DISP_TEXT_SIZE;
2173     if (lvItem.mask) LISTVIEW_GetItemW(infoPtr, &lvItem);
2174     if (uView == LVS_ICON)
2175     {
2176         lvItem.mask |= LVIF_STATE;
2177         lvItem.stateMask = LVIS_FOCUSED;
2178         lvItem.state = (lvItem.mask & LVIF_TEXT ? LVIS_FOCUSED : 0);
2179     }
2180     LISTVIEW_GetItemMetrics(infoPtr, &lvItem, lprcBox, 0, 0, 0, 0);
2181 
2182     OffsetRect(lprcBox, Position.x + Origin.x, Position.y + Origin.y);
2183 }
2184 
2185 
2186 /***
2187  * DESCRIPTION:
2188  * Returns the current icon position, and advances it along the top.
2189  * The returned position is not offset by Origin.
2190  *
2191  * PARAMETER(S):
2192  * [I] infoPtr : valid pointer to the listview structure
2193  * [O] lpPos : will get the current icon position
2194  *
2195  * RETURN:
2196  * None
2197  */
2198 static void LISTVIEW_NextIconPosTop(LISTVIEW_INFO *infoPtr, LPPOINT lpPos)
2199 {
2200     INT nListWidth = infoPtr->rcList.right - infoPtr->rcList.left;
2201     
2202     *lpPos = infoPtr->currIconPos;
2203     
2204     infoPtr->currIconPos.x += infoPtr->nItemWidth;
2205     if (infoPtr->currIconPos.x + infoPtr->nItemWidth <= nListWidth) return;
2206 
2207     infoPtr->currIconPos.x  = 0;
2208     infoPtr->currIconPos.y += infoPtr->nItemHeight;
2209 }
2210 
2211     
2212 /***
2213  * DESCRIPTION:
2214  * Returns the current icon position, and advances it down the left edge.
2215  * The returned position is not offset by Origin.
2216  *
2217  * PARAMETER(S):
2218  * [I] infoPtr : valid pointer to the listview structure
2219  * [O] lpPos : will get the current icon position
2220  *
2221  * RETURN:
2222  * None
2223  */
2224 static void LISTVIEW_NextIconPosLeft(LISTVIEW_INFO *infoPtr, LPPOINT lpPos)
2225 {
2226     INT nListHeight = infoPtr->rcList.bottom - infoPtr->rcList.top;
2227     
2228     *lpPos = infoPtr->currIconPos;
2229     
2230     infoPtr->currIconPos.y += infoPtr->nItemHeight;
2231     if (infoPtr->currIconPos.y + infoPtr->nItemHeight <= nListHeight) return;
2232 
2233     infoPtr->currIconPos.x += infoPtr->nItemWidth;
2234     infoPtr->currIconPos.y  = 0;
2235 }
2236 
2237     
2238 /***
2239  * DESCRIPTION:
2240  * Moves an icon to the specified position.
2241  * It takes care of invalidating the item, etc.
2242  *
2243  * PARAMETER(S):
2244  * [I] infoPtr : valid pointer to the listview structure
2245  * [I] nItem : the item to move
2246  * [I] lpPos : the new icon position
2247  * [I] isNew : flags the item as being new
2248  *
2249  * RETURN:
2250  *   Success: TRUE
2251  *   Failure: FALSE
2252  */
2253 static BOOL LISTVIEW_MoveIconTo(const LISTVIEW_INFO *infoPtr, INT nItem, const POINT *lppt, BOOL isNew)
2254 {
2255     POINT old;
2256     
2257     if (!isNew)
2258     { 
2259         old.x = (LONG_PTR)DPA_GetPtr(infoPtr->hdpaPosX, nItem);
2260         old.y = (LONG_PTR)DPA_GetPtr(infoPtr->hdpaPosY, nItem);
2261     
2262         if (lppt->x == old.x && lppt->y == old.y) return TRUE;
2263         LISTVIEW_InvalidateItem(infoPtr, nItem);
2264     }
2265 
2266     /* Allocating a POINTER for every item is too resource intensive,
2267      * so we'll keep the (x,y) in different arrays */
2268     if (!DPA_SetPtr(infoPtr->hdpaPosX, nItem, (void *)(LONG_PTR)lppt->x)) return FALSE;
2269     if (!DPA_SetPtr(infoPtr->hdpaPosY, nItem, (void *)(LONG_PTR)lppt->y)) return FALSE;
2270 
2271     LISTVIEW_InvalidateItem(infoPtr, nItem);
2272 
2273     return TRUE;
2274 }
2275 
2276 /***
2277  * DESCRIPTION:
2278  * Arranges listview items in icon display mode.
2279  *
2280  * PARAMETER(S):
2281  * [I] infoPtr : valid pointer to the listview structure
2282  * [I] nAlignCode : alignment code
2283  *
2284  * RETURN:
2285  *   SUCCESS : TRUE
2286  *   FAILURE : FALSE
2287  */
2288 static BOOL LISTVIEW_Arrange(LISTVIEW_INFO *infoPtr, INT nAlignCode)
2289 {
2290     UINT uView = infoPtr->dwStyle & LVS_TYPEMASK;
2291     void (*next_pos)(LISTVIEW_INFO *, LPPOINT);
2292     POINT pos;
2293     INT i;
2294 
2295     if (uView != LVS_ICON && uView != LVS_SMALLICON) return FALSE;
2296   
2297     TRACE("nAlignCode=%d\n", nAlignCode);
2298 
2299     if (nAlignCode == LVA_DEFAULT)
2300     {
2301         if (infoPtr->dwStyle & LVS_ALIGNLEFT) nAlignCode = LVA_ALIGNLEFT;
2302         else nAlignCode = LVA_ALIGNTOP;
2303     }
2304    
2305     switch (nAlignCode)
2306     {
2307     case LVA_ALIGNLEFT:  next_pos = LISTVIEW_NextIconPosLeft; break;
2308     case LVA_ALIGNTOP:   next_pos = LISTVIEW_NextIconPosTop;  break;
2309     case LVA_SNAPTOGRID: next_pos = LISTVIEW_NextIconPosTop;  break; /* FIXME */
2310     default: return FALSE;
2311     }
2312     
2313     infoPtr->bAutoarrange = TRUE;
2314     infoPtr->currIconPos.x = infoPtr->currIconPos.y = 0;
2315     for (i = 0; i < infoPtr->nItemCount; i++)
2316     {
2317         next_pos(infoPtr, &pos);
2318         LISTVIEW_MoveIconTo(infoPtr, i, &pos, FALSE);
2319     }
2320 
2321     return TRUE;
2322 }
2323   
2324 /***
2325  * DESCRIPTION:
2326  * Retrieves the bounding rectangle of all the items, not offset by Origin.
2327  *
2328  * PARAMETER(S):
2329  * [I] infoPtr : valid pointer to the listview structure
2330  * [O] lprcView : bounding rectangle
2331  *
2332  * RETURN:
2333  *   SUCCESS : TRUE
2334  *   FAILURE : FALSE
2335  */
2336 static void LISTVIEW_GetAreaRect(const LISTVIEW_INFO *infoPtr, LPRECT lprcView)
2337 {
2338     INT i, x, y;
2339 
2340     SetRectEmpty(lprcView);
2341 
2342     switch (infoPtr->dwStyle & LVS_TYPEMASK)
2343     {
2344     case LVS_ICON:
2345     case LVS_SMALLICON:
2346         for (i = 0; i < infoPtr->nItemCount; i++)
2347         {
2348             x = (LONG_PTR)DPA_GetPtr(infoPtr->hdpaPosX, i);
2349             y = (LONG_PTR)DPA_GetPtr(infoPtr->hdpaPosY, i);
2350             lprcView->right = max(lprcView->right, x);
2351             lprcView->bottom = max(lprcView->bottom, y);
2352         }
2353         if (infoPtr->nItemCount > 0)
2354         {
2355             lprcView->right += infoPtr->nItemWidth;
2356             lprcView->bottom += infoPtr->nItemHeight;
2357         }
2358         break;
2359 
2360     case LVS_LIST:
2361         y = LISTVIEW_GetCountPerColumn(infoPtr);
2362         x = infoPtr->nItemCount / y;
2363         if (infoPtr->nItemCount % y) x++;
2364         lprcView->right = x * infoPtr->nItemWidth;
2365         lprcView->bottom = y * infoPtr->nItemHeight;
2366         break;
2367         
2368     case LVS_REPORT:        
2369         lprcView->right = infoPtr->nItemWidth;
2370         lprcView->bottom = infoPtr->nItemCount * infoPtr->nItemHeight;
2371         break;
2372     }
2373 }
2374 
2375 /***
2376  * DESCRIPTION:
2377  * Retrieves the bounding rectangle of all the items.
2378  *
2379  * PARAMETER(S):
2380  * [I] infoPtr : valid pointer to the listview structure
2381  * [O] lprcView : bounding rectangle
2382  *
2383  * RETURN:
2384  *   SUCCESS : TRUE
2385  *   FAILURE : FALSE
2386  */
2387 static BOOL LISTVIEW_GetViewRect(const LISTVIEW_INFO *infoPtr, LPRECT lprcView)
2388 {
2389     POINT ptOrigin;
2390 
2391     TRACE("(lprcView=%p)\n", lprcView);
2392 
2393     if (!lprcView) return FALSE;
2394  
2395     LISTVIEW_GetOrigin(infoPtr, &ptOrigin);
2396     LISTVIEW_GetAreaRect(infoPtr, lprcView); 
2397     OffsetRect(lprcView, ptOrigin.x, ptOrigin.y); 
2398 
2399     TRACE("lprcView=%s\n", wine_dbgstr_rect(lprcView));
2400 
2401     return TRUE;
2402 }
2403 
2404 /***
2405  * DESCRIPTION:
2406  * Retrieves the subitem pointer associated with the subitem index.
2407  *
2408  * PARAMETER(S):
2409  * [I] hdpaSubItems : DPA handle for a specific item
2410  * [I] nSubItem : index of subitem
2411  *
2412  * RETURN:
2413  *   SUCCESS : subitem pointer
2414  *   FAILURE : NULL
2415  */
2416 static SUBITEM_INFO* LISTVIEW_GetSubItemPtr(HDPA hdpaSubItems, INT nSubItem)
2417 {
2418     SUBITEM_INFO *lpSubItem;
2419     INT i;
2420 
2421     /* we should binary search here if need be */
2422     for (i = 1; i < DPA_GetPtrCount(hdpaSubItems); i++)
2423     {
2424         lpSubItem = (SUBITEM_INFO *)DPA_GetPtr(hdpaSubItems, i);
2425         if (lpSubItem->iSubItem == nSubItem)
2426             return lpSubItem;
2427     }
2428 
2429     return NULL;
2430 }
2431 
2432 
2433 /***
2434  * DESCRIPTION:
2435  * Calculates the desired item width.
2436  *
2437  * PARAMETER(S):
2438  * [I] infoPtr : valid pointer to the listview structure
2439  *
2440  * RETURN:
2441  *  The desired item width.
2442  */
2443 static INT LISTVIEW_CalculateItemWidth(const LISTVIEW_INFO *infoPtr)
2444 {
2445     UINT uView = infoPtr->dwStyle & LVS_TYPEMASK;
2446     INT nItemWidth = 0;
2447 
2448     TRACE("uView=%d\n", uView);
2449 
2450     if (uView == LVS_ICON)
2451         nItemWidth = infoPtr->iconSpacing.cx;
2452     else if (uView == LVS_REPORT)
2453     {
2454         RECT rcHeader;
2455 
2456         if (DPA_GetPtrCount(infoPtr->hdpaColumns) > 0)
2457         {
2458             LISTVIEW_GetHeaderRect(infoPtr, DPA_GetPtrCount(infoPtr->hdpaColumns) - 1, &rcHeader);
2459             nItemWidth = rcHeader.right;
2460         }
2461     }
2462     else /* LVS_SMALLICON, or LVS_LIST */
2463     {
2464         INT i;
2465         
2466         for (i = 0; i < infoPtr->nItemCount; i++)
2467             nItemWidth = max(LISTVIEW_GetLabelWidth(infoPtr, i), nItemWidth);
2468 
2469         if (infoPtr->himlSmall) nItemWidth += infoPtr->iconSize.cx; 
2470         if (infoPtr->himlState) nItemWidth += infoPtr->iconStateSize.cx;
2471 
2472         nItemWidth = max(DEFAULT_COLUMN_WIDTH, nItemWidth + WIDTH_PADDING);
2473     }
2474 
2475     return max(nItemWidth, 1);
2476 }
2477 
2478 /***
2479  * DESCRIPTION:
2480  * Calculates the desired item height.
2481  *
2482  * PARAMETER(S):
2483  * [I] infoPtr : valid pointer to the listview structure
2484  *
2485  * RETURN:
2486  *  The desired item height.
2487  */
2488 static INT LISTVIEW_CalculateItemHeight(const LISTVIEW_INFO *infoPtr)
2489 {
2490     UINT uView = infoPtr->dwStyle & LVS_TYPEMASK;
2491     INT nItemHeight;
2492 
2493     TRACE("uView=%d\n", uView);
2494 
2495     if (uView == LVS_ICON)
2496         nItemHeight = infoPtr->iconSpacing.cy;
2497     else
2498     {
2499         nItemHeight = infoPtr->ntmHeight; 
2500         if (uView == LVS_REPORT && infoPtr->dwLvExStyle & LVS_EX_GRIDLINES)
2501             nItemHeight++;
2502         if (infoPtr->himlState)
2503             nItemHeight = max(nItemHeight, infoPtr->iconStateSize.cy);
2504         if (infoPtr->himlSmall)
2505             nItemHeight = max(nItemHeight, infoPtr->iconSize.cy);
2506         if (infoPtr->himlState || infoPtr->himlSmall)
2507             nItemHeight += HEIGHT_PADDING;
2508     if (infoPtr->nMeasureItemHeight > 0)
2509         nItemHeight = infoPtr->nMeasureItemHeight;
2510     }
2511 
2512     return max(nItemHeight, 1);
2513 }
2514 
2515 /***
2516  * DESCRIPTION:
2517  * Updates the width, and height of an item.
2518  *
2519  * PARAMETER(S):
2520  * [I] infoPtr : valid pointer to the listview structure
2521  *
2522  * RETURN:
2523  *  None.
2524  */
2525 static inline void LISTVIEW_UpdateItemSize(LISTVIEW_INFO *infoPtr)
2526 {
2527     infoPtr->nItemWidth = LISTVIEW_CalculateItemWidth(infoPtr);
2528     infoPtr->nItemHeight = LISTVIEW_CalculateItemHeight(infoPtr);
2529 }
2530 
2531 
2532 /***
2533  * DESCRIPTION:
2534  * Retrieves and saves important text metrics info for the current
2535  * Listview font.
2536  *
2537  * PARAMETER(S):
2538  * [I] infoPtr : valid pointer to the listview structure
2539  *
2540  */
2541 static void LISTVIEW_SaveTextMetrics(LISTVIEW_INFO *infoPtr)
2542 {
2543     HDC hdc = GetDC(infoPtr->hwndSelf);
2544     HFONT hFont = infoPtr->hFont ? infoPtr->hFont : infoPtr->hDefaultFont;
2545     HFONT hOldFont = SelectObject(hdc, hFont);
2546     TEXTMETRICW tm;
2547     SIZE sz;
2548 
2549     if (GetTextMetricsW(hdc, &tm))
2550     {
2551         infoPtr->ntmHeight = tm.tmHeight;
2552         infoPtr->ntmMaxCharWidth = tm.tmMaxCharWidth;
2553     }
2554 
2555     if (GetTextExtentPoint32A(hdc, "...", 3, &sz))
2556         infoPtr->nEllipsisWidth = sz.cx;
2557         
2558     SelectObject(hdc, hOldFont);
2559     ReleaseDC(infoPtr->hwndSelf, hdc);
2560     
2561     TRACE("tmHeight=%d\n", infoPtr->ntmHeight);
2562 }
2563 
2564 /***
2565  * DESCRIPTION:
2566  * A compare function for ranges
2567  *
2568  * PARAMETER(S)
2569  * [I] range1 : pointer to range 1;
2570  * [I] range2 : pointer to range 2;
2571  * [I] flags : flags
2572  *
2573  * RETURNS:
2574  * > 0 : if range 1 > range 2
2575  * < 0 : if range 2 > range 1
2576  * = 0 : if range intersects range 2
2577  */
2578 static INT CALLBACK ranges_cmp(LPVOID range1, LPVOID range2, LPARAM flags)
2579 {
2580     INT cmp;
2581     
2582     if (((RANGE*)range1)->upper <= ((RANGE*)range2)->lower) 
2583         cmp = -1;
2584     else if (((RANGE*)range2)->upper <= ((RANGE*)range1)->lower) 
2585         cmp = 1;
2586     else 
2587         cmp = 0;
2588     
2589     TRACE("range1=%s, range2=%s, cmp=%d\n", debugrange((RANGE*)range1), debugrange((RANGE*)range2), cmp);
2590 
2591     return cmp;
2592 }
2593 
2594 #if DEBUG_RANGES
2595 #define ranges_check(ranges, desc) ranges_assert(ranges, desc, __FUNCTION__, __LINE__)
2596 #else
2597 #define ranges_check(ranges, desc) do { } while(0)
2598 #endif
2599 
2600 static void ranges_assert(RANGES ranges, LPCSTR desc, const char *func, int line)
2601 {
2602     INT i;
2603     RANGE *prev, *curr;
2604     
2605     TRACE("*** Checking %s:%d:%s ***\n", func, line, desc);
2606     assert (ranges);
2607     assert (DPA_GetPtrCount(ranges->hdpa) >= 0);
2608     ranges_dump(ranges);
2609     prev = (RANGE *)DPA_GetPtr(ranges->hdpa, 0);
2610     if (DPA_GetPtrCount(ranges->hdpa) > 0)
2611         assert (prev->lower >= 0 && prev->lower < prev->upper);
2612     for (i = 1; i < DPA_GetPtrCount(ranges->hdpa); i++)
2613     {
2614         curr = (RANGE *)DPA_GetPtr(ranges->hdpa, i);
2615         assert (prev->upper <= curr->lower);
2616         assert (curr->lower < curr->upper);
2617         prev = curr;
2618     }
2619     TRACE("--- Done checking---\n");
2620 }
2621 
2622 static RANGES ranges_create(int count)
2623 {
2624     RANGES ranges = Alloc(sizeof(struct tagRANGES));
2625     if (!ranges) return NULL;
2626     ranges->hdpa = DPA_Create(count);
2627     if (ranges->hdpa) return ranges;
2628     Free(ranges);
2629     return NULL;
2630 }
2631 
2632 static void ranges_clear(RANGES ranges)
2633 {
2634     INT i;
2635         
2636     for(i = 0; i < DPA_GetPtrCount(ranges->hdpa); i++)
2637         Free(DPA_GetPtr(ranges->hdpa, i));
2638     DPA_DeleteAllPtrs(ranges->hdpa);
2639 }
2640 
2641 
2642 static void ranges_destroy(RANGES ranges)
2643 {
2644     if (!ranges) return;
2645     ranges_clear(ranges);
2646     DPA_Destroy(ranges->hdpa);
2647     Free(ranges);
2648 }
2649 
2650 static RANGES ranges_clone(RANGES ranges)
2651 {
2652     RANGES clone;
2653     INT i;
2654            
2655     if (!(clone = ranges_create(DPA_GetPtrCount(ranges->hdpa)))) goto fail;
2656 
2657     for (i = 0; i < DPA_GetPtrCount(ranges->hdpa); i++)
2658     {
2659         RANGE *newrng = Alloc(sizeof(RANGE));
2660         if (!newrng) goto fail;
2661         *newrng = *((RANGE*)DPA_GetPtr(ranges->hdpa, i));
2662         DPA_SetPtr(clone->hdpa, i, newrng);
2663     }
2664     return clone;
2665     
2666 fail:
2667     TRACE ("clone failed\n");
2668     ranges_destroy(clone);
2669     return NULL;
2670 }
2671 
2672 static RANGES ranges_diff(RANGES ranges, RANGES sub)
2673 {
2674     INT i;
2675 
2676     for (i = 0; i < DPA_GetPtrCount(sub->hdpa); i++)
2677         ranges_del(ranges, *((RANGE *)DPA_GetPtr(sub->hdpa, i)));
2678 
2679     return ranges;
2680 }
2681 
2682 static void ranges_dump(RANGES ranges)
2683 {
2684     INT i;
2685 
2686     for (i = 0; i < DPA_GetPtrCount(ranges->hdpa); i++)
2687         TRACE("   %s\n", debugrange(DPA_GetPtr(ranges->hdpa, i)));
2688 }
2689 
2690 static inline BOOL ranges_contain(RANGES ranges, INT nItem)
2691 {
2692     RANGE srchrng = { nItem, nItem + 1 };
2693 
2694     TRACE("(nItem=%d)\n", nItem);
2695     ranges_check(ranges, "before contain");
2696     return DPA_Search(ranges->hdpa, &srchrng, 0, ranges_cmp, 0, DPAS_SORTED) != -1;
2697 }
2698 
2699 static INT ranges_itemcount(RANGES ranges)
2700 {
2701     INT i, count = 0;
2702     
2703     for (i = 0; i < DPA_GetPtrCount(ranges->hdpa); i++)
2704     {
2705         RANGE *sel = DPA_GetPtr(ranges->hdpa, i);
2706         count += sel->upper - sel->lower;
2707     }
2708 
2709     return count;
2710 }
2711 
2712 static BOOL ranges_shift(RANGES ranges, INT nItem, INT delta, INT nUpper)
2713 {
2714     RANGE srchrng = { nItem, nItem + 1 }, *chkrng;
2715     INT index;
2716 
2717     index = DPA_Search(ranges->hdpa, &srchrng, 0, ranges_cmp, 0, DPAS_SORTED | DPAS_INSERTAFTER);
2718     if (index == -1) return TRUE;
2719 
2720     for (; index < DPA_GetPtrCount(ranges->hdpa); index++)
2721     {
2722         chkrng = DPA_GetPtr(ranges->hdpa, index);
2723         if (chkrng->lower >= nItem)
2724             chkrng->lower = max(min(chkrng->lower + delta, nUpper - 1), 0);
2725         if (chkrng->upper > nItem)
2726             chkrng->upper = max(min(chkrng->upper + delta, nUpper), 0);
2727     }
2728     return TRUE;
2729 }
2730 
2731 static BOOL ranges_add(RANGES ranges, RANGE range)
2732 {
2733     RANGE srchrgn;
2734     INT index;
2735 
2736     TRACE("(%s)\n", debugrange(&range));
2737     ranges_check(ranges, "before add");
2738 
2739     /* try find overlapping regions first */
2740     srchrgn.lower = range.lower - 1;
2741     srchrgn.upper = range.upper + 1;
2742     index = DPA_Search(ranges->hdpa, &srchrgn, 0, ranges_cmp, 0, DPAS_SORTED);
2743    
2744     if (index == -1)
2745     {
2746         RANGE *newrgn;
2747 
2748         TRACE("Adding new range\n");
2749 
2750         /* create the brand new range to insert */      
2751         newrgn = Alloc(sizeof(RANGE));
2752         if(!newrgn) goto fail;
2753         *newrgn = range;
2754         
2755         /* figure out where to insert it */
2756         index = DPA_Search(ranges->hdpa, newrgn, 0, ranges_cmp, 0, DPAS_SORTED | DPAS_INSERTAFTER);
2757         TRACE("index=%d\n", index);
2758         if (index == -1) index = 0;
2759         
2760         /* and get it over with */
2761         if (DPA_InsertPtr(ranges->hdpa, index, newrgn) == -1)
2762         {
2763             Free(newrgn);
2764             goto fail;
2765         }
2766     }
2767     else
2768     {
2769         RANGE *chkrgn, *mrgrgn;
2770         INT fromindex, mergeindex;
2771 
2772         chkrgn = DPA_GetPtr(ranges->hdpa, index);
2773         TRACE("Merge with %s @%d\n", debugrange(chkrgn), index);
2774 
2775         chkrgn->lower = min(range.lower, chkrgn->lower);
2776         chkrgn->upper = max(range.upper, chkrgn->upper);
2777         
2778         TRACE("New range %s @%d\n", debugrange(chkrgn), index);
2779 
2780         /* merge now common ranges */
2781         fromindex = 0;
2782         srchrgn.lower = chkrgn->lower - 1;
2783         srchrgn.upper = chkrgn->upper + 1;
2784             
2785         do
2786         {
2787             mergeindex = DPA_Search(ranges->hdpa, &srchrgn, fromindex, ranges_cmp, 0, 0);
2788             if (mergeindex == -1) break;
2789             if (mergeindex == index) 
2790             {
2791                 fromindex = index + 1;
2792                 continue;
2793             }
2794           
2795             TRACE("Merge with index %i\n", mergeindex);
2796             
2797             mrgrgn = DPA_GetPtr(ranges->hdpa, mergeindex);
2798             chkrgn->lower = min(chkrgn->lower, mrgrgn->lower);
2799             chkrgn->upper = max(chkrgn->upper, mrgrgn->upper);
2800             Free(mrgrgn);
2801             DPA_DeletePtr(ranges->hdpa, mergeindex);
2802             if (mergeindex < index) index --;
2803         } while(1);
2804     }
2805 
2806     ranges_check(ranges, "after add");
2807     return TRUE;
2808     
2809 fail:
2810     ranges_check(ranges, "failed add");
2811     return FALSE;
2812 }
2813 
2814 static BOOL ranges_del(RANGES ranges, RANGE range)
2815 {
2816     RANGE *chkrgn;
2817     INT index;
2818 
2819     TRACE("(%s)\n", debugrange(&range));
2820     ranges_check(ranges, "before del");
2821     
2822     /* we don't use DPAS_SORTED here, since we need *
2823      * to find the first overlapping range          */
2824     index = DPA_Search(ranges->hdpa, &range, 0, ranges_cmp, 0, 0);
2825     while(index != -1) 
2826     {
2827         chkrgn = DPA_GetPtr(ranges->hdpa, index);
2828         
2829         TRACE("Matches range %s @%d\n", debugrange(chkrgn), index); 
2830 
2831         /* case 1: Same range */
2832         if ( (chkrgn->upper == range.upper) &&
2833              (chkrgn->lower == range.lower) )
2834         {
2835             DPA_DeletePtr(ranges->hdpa, index);
2836             break;
2837         }
2838         /* case 2: engulf */
2839         else if ( (chkrgn->upper <= range.upper) &&
2840                   (chkrgn->lower >= range.lower) ) 
2841         {
2842             DPA_DeletePtr(ranges->hdpa, index);
2843         }
2844         /* case 3: overlap upper */
2845         else if ( (chkrgn->upper <= range.upper) &&
2846                   (chkrgn->lower < range.lower) )
2847         {
2848             chkrgn->upper = range.lower;
2849         }
2850         /* case 4: overlap lower */
2851         else if ( (chkrgn->upper > range.upper) &&
2852                   (chkrgn->lower >= range.lower) )
2853         {
2854             chkrgn->lower = range.upper;
2855             break;
2856         }
2857         /* case 5: fully internal */
2858         else
2859         {
2860             RANGE tmprgn = *chkrgn, *newrgn;
2861 
2862             if (!(newrgn = Alloc(sizeof(RANGE)))) goto fail;
2863             newrgn->lower = chkrgn->lower;
2864             newrgn->upper = range.lower;
2865             chkrgn->lower = range.upper;
2866             if (DPA_InsertPtr(ranges->hdpa, index, newrgn) == -1)
2867             {
2868                 Free(newrgn);
2869                 goto fail;
2870             }
2871             chkrgn = &tmprgn;
2872             break;
2873         }
2874 
2875         index = DPA_Search(ranges->hdpa, &range, index, ranges_cmp, 0, 0);
2876     }
2877 
2878     ranges_check(ranges, "after del");
2879     return TRUE;
2880 
2881 fail:
2882     ranges_check(ranges, "failed del");
2883     return FALSE;
2884 }
2885 
2886 /***
2887 * DESCRIPTION:
2888 * Removes all selection ranges
2889 *
2890 * Parameters(s):
2891 * [I] infoPtr : valid pointer to the listview structure
2892 * [I] toSkip : item range to skip removing the selection
2893 *
2894 * RETURNS:
2895 *   SUCCESS : TRUE
2896 *   FAILURE : TRUE
2897 */
2898 static BOOL LISTVIEW_DeselectAllSkipItems(LISTVIEW_INFO *infoPtr, RANGES toSkip)
2899 {
2900     LVITEMW lvItem;
2901     ITERATOR i;
2902     RANGES clone;
2903 
2904     TRACE("()\n");
2905 
2906     lvItem.state = 0;
2907     lvItem.stateMask = LVIS_SELECTED;
2908     
2909     /* need to clone the DPA because callbacks can change it */
2910     if (!(clone = ranges_clone(infoPtr->selectionRanges))) return FALSE;
2911     iterator_rangesitems(&i, ranges_diff(clone, toSkip));
2912     while(iterator_next(&i))
2913         LISTVIEW_SetItemState(infoPtr, i.nItem, &lvItem);
2914     /* note that the iterator destructor will free the cloned range */
2915     iterator_destroy(&i);
2916 
2917     return TRUE;
2918 }
2919 
2920 static inline BOOL LISTVIEW_DeselectAllSkipItem(LISTVIEW_INFO *infoPtr, INT nItem)
2921 {
2922     RANGES toSkip;
2923    
2924     if (!(toSkip = ranges_create(1))) return FALSE;
2925     if (nItem != -1) ranges_additem(toSkip, nItem);
2926     LISTVIEW_DeselectAllSkipItems(infoPtr, toSkip);
2927     ranges_destroy(toSkip);
2928     return TRUE;
2929 }
2930 
2931 static inline BOOL LISTVIEW_DeselectAll(LISTVIEW_INFO *infoPtr)
2932 {
2933     return LISTVIEW_DeselectAllSkipItem(infoPtr, -1);
2934 }
2935 
2936 /***
2937  * DESCRIPTION:
2938  * Retrieves the number of items that are marked as selected.
2939  *
2940  * PARAMETER(S):
2941  * [I] infoPtr : valid pointer to the listview structure
2942  *
2943  * RETURN:
2944  * Number of items selected.
2945  */
2946 static INT LISTVIEW_GetSelectedCount(const LISTVIEW_INFO *infoPtr)
2947 {
2948     INT nSelectedCount = 0;
2949 
2950     if (infoPtr->uCallbackMask & LVIS_SELECTED)
2951     {
2952         INT i;
2953         for (i = 0; i < infoPtr->nItemCount; i++)
2954         {
2955             if (LISTVIEW_GetItemState(infoPtr, i, LVIS_SELECTED))
2956                 nSelectedCount++;
2957         }
2958     }
2959     else
2960         nSelectedCount = ranges_itemcount(infoPtr->selectionRanges);
2961 
2962     TRACE("nSelectedCount=%d\n", nSelectedCount);
2963     return nSelectedCount;
2964 }
2965 
2966 /***
2967  * DESCRIPTION:
2968  * Manages the item focus.
2969  *
2970  * PARAMETER(S):
2971  * [I] infoPtr : valid pointer to the listview structure
2972  * [I] nItem : item index
2973  *
2974  * RETURN:
2975  *   TRUE : focused item changed
2976  *   FALSE : focused item has NOT changed
2977  */
2978 static inline BOOL LISTVIEW_SetItemFocus(LISTVIEW_INFO *infoPtr, INT nItem)
2979 {
2980     INT oldFocus = infoPtr->nFocusedItem;
2981     LVITEMW lvItem;
2982 
2983     if (nItem == infoPtr->nFocusedItem) return FALSE;
2984     
2985     lvItem.state =  nItem == -1 ? 0 : LVIS_FOCUSED;
2986     lvItem.stateMask = LVIS_FOCUSED;
2987     LISTVIEW_SetItemState(infoPtr, nItem == -1 ? infoPtr->nFocusedItem : nItem, &lvItem);
2988 
2989     return oldFocus != infoPtr->nFocusedItem;
2990 }
2991 
2992 /* Helper function for LISTVIEW_ShiftIndices *only* */
2993 static INT shift_item(const LISTVIEW_INFO *infoPtr, INT nShiftItem, INT nItem, INT direction)
2994 {
2995     if (nShiftItem < nItem) return nShiftItem;
2996 
2997     if (nShiftItem > nItem) return nShiftItem + direction;
2998 
2999     if (direction > 0) return nShiftItem + direction;
3000 
3001     return min(nShiftItem, infoPtr->nItemCount - 1);
3002 }
3003 
3004 /**
3005 * DESCRIPTION:
3006 * Updates the various indices after an item has been inserted or deleted.
3007 *
3008 * PARAMETER(S):
3009 * [I] infoPtr : valid pointer to the listview structure
3010 * [I] nItem : item index
3011 * [I] direction : Direction of shift, +1 or -1.
3012 *
3013 * RETURN:
3014 * None
3015 */
3016 static void LISTVIEW_ShiftIndices(LISTVIEW_INFO *infoPtr, INT nItem, INT direction)
3017 {
3018     INT nNewFocus;
3019     BOOL bOldChange;
3020 
3021     /* temporarily disable change notification while shifting items */
3022     bOldChange = infoPtr->bDoChangeNotify;
3023     infoPtr->bDoChangeNotify = FALSE;
3024 
3025     TRACE("Shifting %iu, %i steps\n", nItem, direction);
3026 
3027     ranges_shift(infoPtr->selectionRanges, nItem, direction, infoPtr->nItemCount);
3028 
3029     assert(abs(direction) == 1);
3030 
3031     infoPtr->nSelectionMark = shift_item(infoPtr, infoPtr->nSelectionMark, nItem, direction);
3032 
3033     nNewFocus = shift_item(infoPtr, infoPtr->nFocusedItem, nItem, direction);
3034     if (nNewFocus != infoPtr->nFocusedItem)
3035         LISTVIEW_SetItemFocus(infoPtr, nNewFocus);
3036     
3037     /* But we are not supposed to modify nHotItem! */
3038 
3039     infoPtr->bDoChangeNotify = bOldChange;
3040 }
3041 
3042 
3043 /**
3044  * DESCRIPTION:
3045  * Adds a block of selections.
3046  *
3047  * PARAMETER(S):
3048  * [I] infoPtr : valid pointer to the listview structure
3049  * [I] nItem : item index
3050  *
3051  * RETURN:
3052  * Whether the window is still valid.
3053  */
3054 static BOOL LISTVIEW_AddGroupSelection(LISTVIEW_INFO *infoPtr, INT nItem)
3055 {
3056     INT nFirst = min(infoPtr->nSelectionMark, nItem);
3057     INT nLast = max(infoPtr->nSelectionMark, nItem);
3058     HWND hwndSelf = infoPtr->hwndSelf;
3059     NMLVODSTATECHANGE nmlv;
3060     LVITEMW item;
3061     BOOL bOldChange;
3062     INT i;
3063 
3064     /* Temporarily disable change notification
3065      * If the control is LVS_OWNERDATA, we need to send
3066      * only one LVN_ODSTATECHANGED notification.
3067      * See MSDN documentation for LVN_ITEMCHANGED.
3068      */
3069     bOldChange = infoPtr->bDoChangeNotify;
3070     if (infoPtr->dwStyle & LVS_OWNERDATA) infoPtr->bDoChangeNotify = FALSE;
3071 
3072     if (nFirst == -1) nFirst = nItem;
3073 
3074     item.state = LVIS_SELECTED;
3075     item.stateMask = LVIS_SELECTED;
3076 
3077     for (i = nFirst; i <= nLast; i++)
3078         LISTVIEW_SetItemState(infoPtr,i,&item);
3079 
3080     ZeroMemory(&nmlv, sizeof(nmlv));
3081     nmlv.iFrom = nFirst;
3082     nmlv.iTo = nLast;
3083     nmlv.uNewState = 0;
3084     nmlv.uOldState = item.state;
3085 
3086     notify_hdr(infoPtr, LVN_ODSTATECHANGED, (LPNMHDR)&nmlv);
3087     if (!IsWindow(hwndSelf))
3088         return FALSE;
3089     infoPtr->bDoChangeNotify = bOldChange;
3090     return TRUE;
3091 }
3092 
3093 
3094 /***
3095  * DESCRIPTION:
3096  * Sets a single group selection.
3097  *
3098  * PARAMETER(S):
3099  * [I] infoPtr : valid pointer to the listview structure
3100  * [I] nItem : item index
3101  *
3102  * RETURN:
3103  * None
3104  */
3105 static void LISTVIEW_SetGroupSelection(LISTVIEW_INFO *infoPtr, INT nItem)
3106 {
3107     UINT uView = infoPtr->dwStyle & LVS_TYPEMASK;
3108     RANGES selection;
3109     LVITEMW item;
3110     ITERATOR i;
3111     BOOL bOldChange;
3112 
3113     if (!(selection = ranges_create(100))) return;
3114 
3115     item.state = LVIS_SELECTED; 
3116     item.stateMask = LVIS_SELECTED;
3117 
3118     if ((uView == LVS_LIST) || (uView == LVS_REPORT))
3119     {
3120         if (infoPtr->nSelectionMark == -1)
3121         {
3122             infoPtr->nSelectionMark = nItem;
3123             ranges_additem(selection, nItem);
3124         }
3125         else
3126         {
3127             RANGE sel;
3128             
3129             sel.lower = min(infoPtr->nSelectionMark, nItem);
3130             sel.upper = max(infoPtr->nSelectionMark, nItem) + 1;
3131             ranges_add(selection, sel);
3132         }
3133     }
3134     else
3135     {
3136         RECT rcItem, rcSel, rcSelMark;
3137         POINT ptItem;
3138         
3139         rcItem.left = LVIR_BOUNDS;
3140         if (!LISTVIEW_GetItemRect(infoPtr, nItem, &rcItem)) return;
3141         rcSelMark.left = LVIR_BOUNDS;
3142         if (!LISTVIEW_GetItemRect(infoPtr, infoPtr->nSelectionMark, &rcSelMark)) return;
3143         UnionRect(&rcSel, &rcItem, &rcSelMark);
3144         iterator_frameditems(&i, infoPtr, &rcSel);
3145         while(iterator_next(&i))
3146         {
3147             LISTVIEW_GetItemPosition(infoPtr, i.nItem, &ptItem);
3148             if (PtInRect(&rcSel, ptItem)) ranges_additem(selection, i.nItem);
3149         }
3150         iterator_destroy(&i);
3151     }
3152 
3153     bOldChange = infoPtr->bDoChangeNotify;
3154     infoPtr->bDoChangeNotify = FALSE;
3155 
3156     LISTVIEW_DeselectAllSkipItems(infoPtr, selection);
3157 
3158 
3159     iterator_rangesitems(&i, selection);
3160     while(iterator_next(&i))
3161         LISTVIEW_SetItemState(infoPtr, i.nItem, &item);
3162     /* this will also destroy the selection */
3163     iterator_destroy(&i);
3164 
3165     infoPtr->bDoChangeNotify = bOldChange;
3166     
3167     LISTVIEW_SetItemFocus(infoPtr, nItem);
3168 }
3169 
3170 /***
3171  * DESCRIPTION:
3172  * Sets a single selection.
3173  *
3174  * PARAMETER(S):
3175  * [I] infoPtr : valid pointer to the listview structure
3176  * [I] nItem : item index
3177  *
3178  * RETURN:
3179  * None
3180  */
3181 static void LISTVIEW_SetSelection(LISTVIEW_INFO *infoPtr, INT nItem)
3182 {
3183     LVITEMW lvItem;
3184 
3185     TRACE("nItem=%d\n", nItem);
3186     
3187     LISTVIEW_DeselectAllSkipItem(infoPtr, nItem);
3188 
3189     lvItem.state = LVIS_FOCUSED | LVIS_SELECTED;
3190     lvItem.stateMask = LVIS_FOCUSED | LVIS_SELECTED;
3191     LISTVIEW_SetItemState(infoPtr, nItem, &lvItem);
3192 
3193     infoPtr->nSelectionMark = nItem;
3194 }
3195 
3196 /***
3197  * DESCRIPTION:
3198  * Set selection(s) with keyboard.
3199  *
3200  * PARAMETER(S):
3201  * [I] infoPtr : valid pointer to the listview structure
3202  * [I] nItem : item index
3203  *
3204  * RETURN:
3205  *   SUCCESS : TRUE (needs to be repainted)
3206  *   FAILURE : FALSE (nothing has changed)
3207  */
3208 static BOOL LISTVIEW_KeySelection(LISTVIEW_INFO *infoPtr, INT nItem)
3209 {
3210   /* FIXME: pass in the state */
3211   WORD wShift = HIWORD(GetKeyState(VK_SHIFT));
3212   WORD wCtrl = HIWORD(GetKeyState(VK_CONTROL));
3213   BOOL bResult = FALSE;
3214 
3215   TRACE("nItem=%d, wShift=%d, wCtrl=%d\n", nItem, wShift, wCtrl);
3216   if ((nItem >= 0) && (nItem < infoPtr->nItemCount))
3217   {
3218     if (infoPtr->dwStyle & LVS_SINGLESEL)
3219     {
3220       bResult = TRUE;
3221       LISTVIEW_SetSelection(infoPtr, nItem);
3222     }
3223     else
3224     {
3225       if (wShift)
3226       {
3227         bResult = TRUE;
3228         LISTVIEW_SetGroupSelection(infoPtr, nItem);
3229       }
3230       else if (wCtrl)
3231       {
3232         LVITEMW lvItem;
3233         lvItem.state = ~LISTVIEW_GetItemState(infoPtr, nItem, LVIS_SELECTED);
3234         lvItem.stateMask = LVIS_SELECTED;
3235         LISTVIEW_SetItemState(infoPtr, nItem, &lvItem);
3236 
3237         if (lvItem.state & LVIS_SELECTED)
3238             infoPtr->nSelectionMark = nItem;
3239 
3240         bResult = LISTVIEW_SetItemFocus(infoPtr, nItem);
3241       }
3242       else
3243       {
3244         bResult = TRUE;
3245         LISTVIEW_SetSelection(infoPtr, nItem);
3246       }
3247     }
3248     LISTVIEW_EnsureVisible(infoPtr, nItem, FALSE);
3249   }
3250 
3251   UpdateWindow(infoPtr->hwndSelf); /* update client area */
3252   return bResult;
3253 }
3254 
3255 static BOOL LISTVIEW_GetItemAtPt(const LISTVIEW_INFO *infoPtr, LPLVITEMW lpLVItem, POINT pt)
3256 {
3257     LVHITTESTINFO lvHitTestInfo;
3258 
3259     ZeroMemory(&lvHitTestInfo, sizeof(lvHitTestInfo));
3260     lvHitTestInfo.pt.x = pt.x;
3261     lvHitTestInfo.pt.y = pt.y;
3262 
3263     LISTVIEW_HitTest(infoPtr, &lvHitTestInfo, TRUE, FALSE);
3264 
3265     lpLVItem->mask = LVIF_PARAM;
3266     lpLVItem->iItem = lvHitTestInfo.iItem;
3267     lpLVItem->iSubItem = 0;
3268 
3269     return LISTVIEW_GetItemT(infoPtr, lpLVItem, TRUE);
3270 }
3271 
3272 /***
3273  * DESCRIPTION:
3274  * Called when the mouse is being actively tracked and has hovered for a specified
3275  * amount of time
3276  *
3277  * PARAMETER(S):
3278  * [I] infoPtr : valid pointer to the listview structure
3279  * [I] fwKeys : key indicator
3280  * [I] x,y : mouse position
3281  *
3282  * RETURN:
3283  *   0 if the message was processed, non-zero if there was an error
3284  *
3285  * INFO:
3286  * LVS_EX_TRACKSELECT: An item is automatically selected when the cursor remains
3287  * over the item for a certain period of time.
3288  *
3289  */
3290 static LRESULT LISTVIEW_MouseHover(LISTVIEW_INFO *infoPtr, WORD fwKeys, INT x, INT y)
3291 {
3292     if (infoPtr->dwLvExStyle & LVS_EX_TRACKSELECT)
3293     {
3294         LVITEMW item;
3295         POINT pt;
3296 
3297         pt.x = x;
3298         pt.y = y;
3299 
3300         if (LISTVIEW_GetItemAtPt(infoPtr, &item, pt))
3301             LISTVIEW_SetSelection(infoPtr, item.iItem);
3302     }
3303 
3304     return 0;
3305 }
3306 
3307 /***
3308  * DESCRIPTION:
3309  * Called whenever WM_MOUSEMOVE is received.
3310  *
3311  * PARAMETER(S):
3312  * [I] infoPtr : valid pointer to the listview structure
3313  * [I] fwKeys : key indicator
3314  * [I] x,y : mouse position
3315  *
3316  * RETURN:
3317  *   0 if the message is processed, non-zero if there was an error
3318  */
3319 static LRESULT LISTVIEW_MouseMove(LISTVIEW_INFO *infoPtr, WORD fwKeys, INT x, INT y)
3320 {
3321     TRACKMOUSEEVENT trackinfo;
3322 
3323     if (!(fwKeys & MK_LBUTTON))
3324         infoPtr->bLButtonDown = FALSE;
3325 
3326     if (infoPtr->bLButtonDown)
3327     {
3328         MSG msg;
3329         BOOL skip = FALSE;
3330         /* Check to see if we got a WM_LBUTTONUP, and skip the DragDetect.
3331          * Otherwise, DragDetect will eat it.
3332          */
3333         if (PeekMessageW(&msg, 0, WM_MOUSEFIRST, WM_MOUSELAST, PM_NOREMOVE))
3334             if (msg.message == WM_LBUTTONUP)
3335                 skip = TRUE;
3336 
3337         if (!skip && DragDetect(infoPtr->hwndSelf, infoPtr->ptClickPos))
3338         {
3339             LVHITTESTINFO lvHitTestInfo;
3340             NMLISTVIEW nmlv;
3341 
3342             lvHitTestInfo.pt = infoPtr->ptClickPos;
3343             LISTVIEW_HitTest(infoPtr, &lvHitTestInfo, TRUE, TRUE);
3344 
3345             ZeroMemory(&nmlv, sizeof(nmlv));
3346             nmlv.iItem = lvHitTestInfo.iItem;
3347             nmlv.ptAction = infoPtr->ptClickPos;
3348 
3349             if (!infoPtr->bDragging)
3350             {
3351                 notify_listview(infoPtr, LVN_BEGINDRAG, &nmlv);
3352                 infoPtr->bDragging = TRUE;
3353             }
3354 
3355             return 0;
3356         }
3357     }
3358     else
3359         infoPtr->bLButtonDown = FALSE;
3360 
3361     /* see if we are supposed to be tracking mouse hovering */
3362     if(infoPtr->dwLvExStyle & LVS_EX_TRACKSELECT) {
3363         /* fill in the trackinfo struct */
3364         trackinfo.cbSize = sizeof(TRACKMOUSEEVENT);
3365         trackinfo.dwFlags = TME_QUERY;
3366         trackinfo.hwndTrack = infoPtr->hwndSelf;
3367         trackinfo.dwHoverTime = infoPtr->dwHoverTime;
3368 
3369         /* see if we are already tracking this hwnd */
3370         _TrackMouseEvent(&trackinfo);
3371 
3372         if(!(trackinfo.dwFlags & TME_HOVER)) {
3373             trackinfo.dwFlags = TME_HOVER;
3374 
3375             /* call TRACKMOUSEEVENT so we receive WM_MOUSEHOVER messages */
3376             _TrackMouseEvent(&trackinfo);
3377         }
3378     }
3379 
3380     return 0;
3381 }
3382 
3383 
3384 /***
3385  * Tests whether the item is assignable to a list with style lStyle
3386  */
3387 static inline BOOL is_assignable_item(const LVITEMW *lpLVItem, LONG lStyle)
3388 {
3389     if ( (lpLVItem->mask & LVIF_TEXT) && 
3390         (lpLVItem->pszText == LPSTR_TEXTCALLBACKW) &&
3391         (lStyle & (LVS_SORTASCENDING | LVS_SORTDESCENDING)) ) return FALSE;
3392     
3393     return TRUE;
3394 }
3395 
3396 
3397 /***
3398  * DESCRIPTION:
3399  * Helper for LISTVIEW_SetItemT *only*: sets item attributes.
3400  *
3401  * PARAMETER(S):
3402  * [I] infoPtr : valid pointer to the listview structure
3403  * [I] lpLVItem : valid pointer to new item attributes
3404  * [I] isNew : the item being set is being inserted
3405  * [I] isW : TRUE if lpLVItem is Unicode, FALSE if it's ANSI
3406  * [O] bChanged : will be set to TRUE if the item really changed
3407  *
3408  * RETURN:
3409  *   SUCCESS : TRUE
3410  *   FAILURE : FALSE
3411  */
3412 static BOOL set_main_item(LISTVIEW_INFO *infoPtr, const LVITEMW *lpLVItem, BOOL isNew, BOOL isW, BOOL *bChanged)
3413 {
3414     UINT uView = infoPtr->dwStyle & LVS_TYPEMASK;
3415     ITEM_INFO *lpItem;
3416     NMLISTVIEW nmlv;
3417     UINT uChanged = 0;
3418     LVITEMW item;
3419 
3420     TRACE("()\n");
3421 
3422     assert(lpLVItem->iItem >= 0 && lpLVItem->iItem < infoPtr->nItemCount);
3423     
3424     if (lpLVItem->mask == 0) return TRUE;   
3425 
3426     if (infoPtr->dwStyle & LVS_OWNERDATA)
3427     {
3428         /* a virtual listview only stores selection and focus */
3429         if (lpLVItem->mask & ~LVIF_STATE)
3430             return FALSE;
3431         lpItem = NULL;
3432     }
3433     else
3434     {
3435         HDPA hdpaSubItems = (HDPA)DPA_GetPtr(infoPtr->hdpaItems, lpLVItem->iItem);
3436         lpItem = (ITEM_INFO *)DPA_GetPtr(hdpaSubItems, 0);
3437         assert (lpItem);
3438     }
3439 
3440     /* we need to get the lParam and state of the item */
3441     item.iItem = lpLVItem->iItem;
3442     item.iSubItem = lpLVItem->iSubItem;
3443     item.mask = LVIF_STATE | LVIF_PARAM;
3444     item.stateMask = ~0;
3445     item.state = 0;
3446     item.lParam = 0;
3447     if (!isNew && !LISTVIEW_GetItemW(infoPtr, &item)) return FALSE;
3448 
3449     TRACE("oldState=%x, newState=%x\n", item.state, lpLVItem->state);
3450     /* determine what fields will change */    
3451     if ((lpLVItem->mask & LVIF_STATE) && ((item.state ^ lpLVItem->state) & lpLVItem->stateMask & ~infoPtr->uCallbackMask))
3452         uChanged |= LVIF_STATE;
3453 
3454     if ((lpLVItem->mask & LVIF_IMAGE) && (lpItem->hdr.iImage != lpLVItem->iImage))
3455         uChanged |= LVIF_IMAGE;
3456 
3457     if ((lpLVItem->mask & LVIF_PARAM) && (lpItem->lParam != lpLVItem->lParam))
3458         uChanged |= LVIF_PARAM;
3459 
3460     if ((lpLVItem->mask & LVIF_INDENT) && (lpItem->iIndent != lpLVItem->iIndent))
3461         uChanged |= LVIF_INDENT;
3462 
3463     if ((lpLVItem->mask & LVIF_TEXT) && textcmpWT(lpItem->hdr.pszText, lpLVItem->pszText, isW))
3464         uChanged |= LVIF_TEXT;
3465    
3466     TRACE("uChanged=0x%x\n", uChanged); 
3467     if (!uChanged) return TRUE;
3468     *bChanged = TRUE;
3469     
3470     ZeroMemory(&nmlv, sizeof(NMLISTVIEW));
3471     nmlv.iItem = lpLVItem->iItem;
3472     nmlv.uNewState = (item.state & ~lpLVItem->stateMask) | (lpLVItem->state & lpLVItem->stateMask);
3473     nmlv.uOldState = item.state;
3474     nmlv.uChanged = uChanged;
3475     nmlv.lParam = item.lParam;
3476     
3477     /* send LVN_ITEMCHANGING notification, if the item is not being inserted */
3478     /* and we are _NOT_ virtual (LVS_OWNERDATA), and change notifications */
3479     /* are enabled */
3480     if(lpItem && !isNew && infoPtr->bDoChangeNotify)
3481     {
3482       HWND hwndSelf = infoPtr->hwndSelf;
3483 
3484       if (notify_listview(infoPtr, LVN_ITEMCHANGING, &nmlv))
3485         return FALSE;
3486       if (!IsWindow(hwndSelf))
3487         return FALSE;
3488     }
3489 
3490     /* copy information */
3491     if (lpLVItem->mask & LVIF_TEXT)
3492         textsetptrT(&lpItem->hdr.pszText, lpLVItem->pszText, isW);
3493 
3494     if (lpLVItem->mask & LVIF_IMAGE)
3495         lpItem->hdr.iImage = lpLVItem->iImage;