Rename wxCharCode{MSWToWX,WXToMSW}() and move them to a separate header.
[wxWidgets.git] / src / msw / listctrl.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/listctrl.cpp
3 // Purpose: wxListCtrl
4 // Author: Julian Smart
5 // Modified by: Agron Selimaj
6 // Created: 04/01/98
7 // RCS-ID: $Id$
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24 #pragma hdrstop
25 #endif
26
27 #if wxUSE_LISTCTRL
28
29 #include "wx/listctrl.h"
30
31 #ifndef WX_PRECOMP
32 #include "wx/msw/wrapcctl.h" // include <commctrl.h> "properly"
33 #include "wx/app.h"
34 #include "wx/intl.h"
35 #include "wx/log.h"
36 #include "wx/settings.h"
37 #include "wx/dcclient.h"
38 #include "wx/textctrl.h"
39 #endif
40
41 #include "wx/imaglist.h"
42 #include "wx/vector.h"
43
44 #include "wx/msw/private.h"
45 #include "wx/msw/private/keyboard.h"
46
47 #if defined(__WXWINCE__) && !defined(__HANDHELDPC__)
48 #include <ole2.h>
49 #include <shellapi.h>
50 #if _WIN32_WCE < 400
51 #include <aygshell.h>
52 #endif
53 #endif
54
55 // Currently gcc and watcom don't define NMLVFINDITEM, and DMC only defines
56 // it by its old name NM_FINDTIEM.
57 //
58 #if defined(__VISUALC__) || defined(__BORLANDC__) || defined(NMLVFINDITEM)
59 #define HAVE_NMLVFINDITEM 1
60 #elif defined(__DMC__) || defined(NM_FINDITEM)
61 #define HAVE_NMLVFINDITEM 1
62 #define NMLVFINDITEM NM_FINDITEM
63 #endif
64
65 // ----------------------------------------------------------------------------
66 // private functions
67 // ----------------------------------------------------------------------------
68
69 // convert our state and mask flags to LV_ITEM constants
70 static void wxConvertToMSWFlags(long state, long mask, LV_ITEM& lvItem);
71
72 // convert wxListItem to LV_ITEM
73 static void wxConvertToMSWListItem(const wxListCtrl *ctrl,
74 const wxListItem& info, LV_ITEM& lvItem);
75
76 // convert LV_ITEM to wxListItem
77 static void wxConvertFromMSWListItem(HWND hwndListCtrl,
78 wxListItem& info,
79 /* const */ LV_ITEM& lvItem);
80
81 // convert our wxListItem to LV_COLUMN
82 static void wxConvertToMSWListCol(HWND hwndList,
83 int col,
84 const wxListItem& item,
85 LV_COLUMN& lvCol);
86
87 namespace
88 {
89
90 // replacement for ListView_GetSubItemRect() which provokes warnings like
91 // "the address of 'rc' will always evaluate as 'true'" when used with mingw32
92 // 4.3+
93 //
94 // this function does no error checking on item and subitem parameters, notice
95 // that subitem 0 means the whole item so there is no way to retrieve the
96 // rectangle of the first subitem using this function, in particular notice
97 // that the index is *not* 1-based, in spite of what MSDN says
98 inline bool
99 wxGetListCtrlSubItemRect(HWND hwnd, int item, int subitem, int flags, RECT& rect)
100 {
101 rect.top = subitem;
102 rect.left = flags;
103 return ::SendMessage(hwnd, LVM_GETSUBITEMRECT, item, (LPARAM)&rect) != 0;
104 }
105
106 inline bool
107 wxGetListCtrlItemRect(HWND hwnd, int item, int flags, RECT& rect)
108 {
109 return wxGetListCtrlSubItemRect(hwnd, item, 0, flags, rect);
110 }
111
112 } // anonymous namespace
113
114 // ----------------------------------------------------------------------------
115 // private helper classes
116 // ----------------------------------------------------------------------------
117
118 // We have to handle both fooW and fooA notifications in several cases
119 // because of broken comctl32.dll and/or unicows.dll. This class is used to
120 // convert LV_ITEMA and LV_ITEMW to LV_ITEM (which is either LV_ITEMA or
121 // LV_ITEMW depending on wxUSE_UNICODE setting), so that it can be processed
122 // by wxConvertToMSWListItem().
123 #if wxUSE_UNICODE
124 #define LV_ITEM_NATIVE LV_ITEMW
125 #define LV_ITEM_OTHER LV_ITEMA
126
127 #define LV_CONV_TO_WX cMB2WX
128 #define LV_CONV_BUF wxMB2WXbuf
129 #else // ANSI
130 #define LV_ITEM_NATIVE LV_ITEMA
131 #define LV_ITEM_OTHER LV_ITEMW
132
133 #define LV_CONV_TO_WX cWC2WX
134 #define LV_CONV_BUF wxWC2WXbuf
135 #endif // Unicode/ANSI
136
137 class wxLV_ITEM
138 {
139 public:
140 // default ctor, use Init() later
141 wxLV_ITEM() { m_buf = NULL; m_pItem = NULL; }
142
143 // init without conversion
144 void Init(LV_ITEM_NATIVE& item)
145 {
146 wxASSERT_MSG( !m_pItem, wxT("Init() called twice?") );
147
148 m_pItem = &item;
149 }
150
151 // init with conversion
152 void Init(const LV_ITEM_OTHER& item)
153 {
154 // avoid unnecessary dynamic memory allocation, jjust make m_pItem
155 // point to our own m_item
156
157 // memcpy() can't work if the struct sizes are different
158 wxCOMPILE_TIME_ASSERT( sizeof(LV_ITEM_OTHER) == sizeof(LV_ITEM_NATIVE),
159 CodeCantWorkIfDiffSizes);
160
161 memcpy(&m_item, &item, sizeof(LV_ITEM_NATIVE));
162
163 // convert text from ANSI to Unicod if necessary
164 if ( (item.mask & LVIF_TEXT) && item.pszText )
165 {
166 m_buf = new LV_CONV_BUF(wxConvLocal.LV_CONV_TO_WX(item.pszText));
167 m_item.pszText = (wxChar *)m_buf->data();
168 }
169 }
170
171 // ctor without conversion
172 wxLV_ITEM(LV_ITEM_NATIVE& item) : m_buf(NULL), m_pItem(&item) { }
173
174 // ctor with conversion
175 wxLV_ITEM(LV_ITEM_OTHER& item) : m_buf(NULL)
176 {
177 Init(item);
178 }
179
180 ~wxLV_ITEM() { delete m_buf; }
181
182 // conversion to the real LV_ITEM
183 operator LV_ITEM_NATIVE&() const { return *m_pItem; }
184
185 private:
186 LV_CONV_BUF *m_buf;
187
188 LV_ITEM_NATIVE *m_pItem;
189 LV_ITEM_NATIVE m_item;
190
191 wxDECLARE_NO_COPY_CLASS(wxLV_ITEM);
192 };
193
194 ///////////////////////////////////////////////////////
195 // Problem:
196 // The MSW version had problems with SetTextColour() et
197 // al as the wxListItemAttr's were stored keyed on the
198 // item index. If a item was inserted anywhere but the end
199 // of the list the text attributes (colour etc) for
200 // the following items were out of sync.
201 //
202 // Solution:
203 // Under MSW the only way to associate data with a List
204 // item independent of its position in the list is to
205 // store a pointer to it in its lParam attribute. However
206 // user programs are already using this (via the
207 // SetItemData() GetItemData() calls).
208 //
209 // However what we can do is store a pointer to a
210 // structure which contains the attributes we want *and*
211 // a lParam -- and this is what wxMSWListItemData does.
212 //
213 // To conserve memory, a wxMSWListItemData is
214 // only allocated for a LV_ITEM if text attributes or
215 // user data(lparam) are being set.
216 class wxMSWListItemData
217 {
218 public:
219 wxMSWListItemData() : attr(NULL), lParam(0) {}
220 ~wxMSWListItemData() { delete attr; }
221
222 wxListItemAttr *attr;
223 LPARAM lParam; // real user data
224
225 wxDECLARE_NO_COPY_CLASS(wxMSWListItemData);
226 };
227
228 #if wxUSE_EXTENDED_RTTI
229 WX_DEFINE_FLAGS( wxListCtrlStyle )
230
231 wxBEGIN_FLAGS( wxListCtrlStyle )
232 // new style border flags, we put them first to
233 // use them for streaming out
234 wxFLAGS_MEMBER(wxBORDER_SIMPLE)
235 wxFLAGS_MEMBER(wxBORDER_SUNKEN)
236 wxFLAGS_MEMBER(wxBORDER_DOUBLE)
237 wxFLAGS_MEMBER(wxBORDER_RAISED)
238 wxFLAGS_MEMBER(wxBORDER_STATIC)
239 wxFLAGS_MEMBER(wxBORDER_NONE)
240
241 // old style border flags
242 wxFLAGS_MEMBER(wxSIMPLE_BORDER)
243 wxFLAGS_MEMBER(wxSUNKEN_BORDER)
244 wxFLAGS_MEMBER(wxDOUBLE_BORDER)
245 wxFLAGS_MEMBER(wxRAISED_BORDER)
246 wxFLAGS_MEMBER(wxSTATIC_BORDER)
247 wxFLAGS_MEMBER(wxBORDER)
248
249 // standard window styles
250 wxFLAGS_MEMBER(wxTAB_TRAVERSAL)
251 wxFLAGS_MEMBER(wxCLIP_CHILDREN)
252 wxFLAGS_MEMBER(wxTRANSPARENT_WINDOW)
253 wxFLAGS_MEMBER(wxWANTS_CHARS)
254 wxFLAGS_MEMBER(wxFULL_REPAINT_ON_RESIZE)
255 wxFLAGS_MEMBER(wxALWAYS_SHOW_SB )
256 wxFLAGS_MEMBER(wxVSCROLL)
257 wxFLAGS_MEMBER(wxHSCROLL)
258
259 wxFLAGS_MEMBER(wxLC_LIST)
260 wxFLAGS_MEMBER(wxLC_REPORT)
261 wxFLAGS_MEMBER(wxLC_ICON)
262 wxFLAGS_MEMBER(wxLC_SMALL_ICON)
263 wxFLAGS_MEMBER(wxLC_ALIGN_TOP)
264 wxFLAGS_MEMBER(wxLC_ALIGN_LEFT)
265 wxFLAGS_MEMBER(wxLC_AUTOARRANGE)
266 wxFLAGS_MEMBER(wxLC_USER_TEXT)
267 wxFLAGS_MEMBER(wxLC_EDIT_LABELS)
268 wxFLAGS_MEMBER(wxLC_NO_HEADER)
269 wxFLAGS_MEMBER(wxLC_SINGLE_SEL)
270 wxFLAGS_MEMBER(wxLC_SORT_ASCENDING)
271 wxFLAGS_MEMBER(wxLC_SORT_DESCENDING)
272 wxFLAGS_MEMBER(wxLC_VIRTUAL)
273
274 wxEND_FLAGS( wxListCtrlStyle )
275
276 IMPLEMENT_DYNAMIC_CLASS_XTI(wxListCtrl, wxControl,"wx/listctrl.h")
277
278 wxBEGIN_PROPERTIES_TABLE(wxListCtrl)
279 wxEVENT_PROPERTY( TextUpdated , wxEVT_COMMAND_TEXT_UPDATED , wxCommandEvent )
280
281 wxPROPERTY_FLAGS( WindowStyle , wxListCtrlStyle , long , SetWindowStyleFlag , GetWindowStyleFlag , EMPTY_MACROVALUE , 0 /*flags*/ , wxT("Helpstring") , wxT("group")) // style
282 wxEND_PROPERTIES_TABLE()
283
284 wxBEGIN_HANDLERS_TABLE(wxListCtrl)
285 wxEND_HANDLERS_TABLE()
286
287 wxCONSTRUCTOR_5( wxListCtrl , wxWindow* , Parent , wxWindowID , Id , wxPoint , Position , wxSize , Size , long , WindowStyle )
288
289 /*
290 TODO : Expose more information of a list's layout etc. via appropriate objects (a la NotebookPageInfo)
291 */
292 #else
293 IMPLEMENT_DYNAMIC_CLASS(wxListCtrl, wxControl)
294 #endif
295
296 IMPLEMENT_DYNAMIC_CLASS(wxListView, wxListCtrl)
297 IMPLEMENT_DYNAMIC_CLASS(wxListItem, wxObject)
298
299 IMPLEMENT_DYNAMIC_CLASS(wxListEvent, wxNotifyEvent)
300
301 BEGIN_EVENT_TABLE(wxListCtrl, wxControl)
302 EVT_PAINT(wxListCtrl::OnPaint)
303 END_EVENT_TABLE()
304
305 // ============================================================================
306 // implementation
307 // ============================================================================
308
309 // ----------------------------------------------------------------------------
310 // wxListCtrl construction
311 // ----------------------------------------------------------------------------
312
313 void wxListCtrl::Init()
314 {
315 m_imageListNormal =
316 m_imageListSmall =
317 m_imageListState = NULL;
318 m_ownsImageListNormal =
319 m_ownsImageListSmall =
320 m_ownsImageListState = false;
321
322 m_colCount = 0;
323 m_count = 0;
324 m_textCtrl = NULL;
325
326 m_hasAnyAttr = false;
327 }
328
329 bool wxListCtrl::Create(wxWindow *parent,
330 wxWindowID id,
331 const wxPoint& pos,
332 const wxSize& size,
333 long style,
334 const wxValidator& validator,
335 const wxString& name)
336 {
337 if ( !CreateControl(parent, id, pos, size, style, validator, name) )
338 return false;
339
340 if ( !MSWCreateControl(WC_LISTVIEW, wxEmptyString, pos, size) )
341 return false;
342
343 // explicitly say that we want to use Unicode because otherwise we get ANSI
344 // versions of _some_ messages (notably LVN_GETDISPINFOA) in MSLU build
345 wxSetCCUnicodeFormat(GetHwnd());
346
347 // We must set the default text colour to the system/theme color, otherwise
348 // GetTextColour will always return black
349 SetTextColour(GetDefaultAttributes().colFg);
350
351 if ( InReportView() )
352 MSWSetExListStyles();
353
354 return true;
355 }
356
357 void wxListCtrl::MSWSetExListStyles()
358 {
359 // for comctl32.dll v 4.70+ we want to have some non default extended
360 // styles because it's prettier (and also because wxGTK does it like this)
361 if ( wxApp::GetComCtl32Version() >= 470 )
362 {
363 ::SendMessage
364 (
365 GetHwnd(), LVM_SETEXTENDEDLISTVIEWSTYLE, 0,
366 // LVS_EX_LABELTIP shouldn't be used under Windows CE where it's
367 // not defined in the SDK headers
368 #ifdef LVS_EX_LABELTIP
369 LVS_EX_LABELTIP |
370 #endif
371 LVS_EX_FULLROWSELECT |
372 LVS_EX_SUBITEMIMAGES |
373 // normally this should be governed by a style as it's probably not
374 // always appropriate, but we don't have any free styles left and
375 // it seems better to enable it by default than disable
376 LVS_EX_HEADERDRAGDROP
377 );
378 }
379 }
380
381 WXDWORD wxListCtrl::MSWGetStyle(long style, WXDWORD *exstyle) const
382 {
383 WXDWORD wstyle = wxControl::MSWGetStyle(style, exstyle);
384
385 wstyle |= LVS_SHAREIMAGELISTS | LVS_SHOWSELALWAYS;
386
387 #if wxDEBUG_LEVEL
388 size_t nModes = 0;
389
390 #define MAP_MODE_STYLE(wx, ms) \
391 if ( style & (wx) ) { wstyle |= (ms); nModes++; }
392 #else // !wxDEBUG_LEVEL
393 #define MAP_MODE_STYLE(wx, ms) \
394 if ( style & (wx) ) wstyle |= (ms);
395 #endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
396
397 MAP_MODE_STYLE(wxLC_ICON, LVS_ICON)
398 MAP_MODE_STYLE(wxLC_SMALL_ICON, LVS_SMALLICON)
399 MAP_MODE_STYLE(wxLC_LIST, LVS_LIST)
400 MAP_MODE_STYLE(wxLC_REPORT, LVS_REPORT)
401
402 wxASSERT_MSG( nModes == 1,
403 wxT("wxListCtrl style should have exactly one mode bit set") );
404
405 #undef MAP_MODE_STYLE
406
407 if ( style & wxLC_ALIGN_LEFT )
408 wstyle |= LVS_ALIGNLEFT;
409
410 if ( style & wxLC_ALIGN_TOP )
411 wstyle |= LVS_ALIGNTOP;
412
413 if ( style & wxLC_AUTOARRANGE )
414 wstyle |= LVS_AUTOARRANGE;
415
416 if ( style & wxLC_NO_SORT_HEADER )
417 wstyle |= LVS_NOSORTHEADER;
418
419 if ( style & wxLC_NO_HEADER )
420 wstyle |= LVS_NOCOLUMNHEADER;
421
422 if ( style & wxLC_EDIT_LABELS )
423 wstyle |= LVS_EDITLABELS;
424
425 if ( style & wxLC_SINGLE_SEL )
426 wstyle |= LVS_SINGLESEL;
427
428 if ( style & wxLC_SORT_ASCENDING )
429 {
430 wstyle |= LVS_SORTASCENDING;
431
432 wxASSERT_MSG( !(style & wxLC_SORT_DESCENDING),
433 wxT("can't sort in ascending and descending orders at once") );
434 }
435 else if ( style & wxLC_SORT_DESCENDING )
436 wstyle |= LVS_SORTDESCENDING;
437
438 #if !( defined(__GNUWIN32__) && !wxCHECK_W32API_VERSION( 1, 0 ) )
439 if ( style & wxLC_VIRTUAL )
440 {
441 int ver = wxApp::GetComCtl32Version();
442 if ( ver < 470 )
443 {
444 wxLogWarning(_("Please install a newer version of comctl32.dll\n(at least version 4.70 is required but you have %d.%02d)\nor this program won't operate correctly."),
445 ver / 100, ver % 100);
446 }
447
448 wstyle |= LVS_OWNERDATA;
449 }
450 #endif // ancient cygwin
451
452 return wstyle;
453 }
454
455 void wxListCtrl::UpdateStyle()
456 {
457 if ( GetHwnd() )
458 {
459 // The new window view style
460 DWORD dwStyleNew = MSWGetStyle(m_windowStyle, NULL);
461
462 // some styles are not returned by MSWGetStyle()
463 if ( IsShown() )
464 dwStyleNew |= WS_VISIBLE;
465
466 // Get the current window style.
467 DWORD dwStyleOld = ::GetWindowLong(GetHwnd(), GWL_STYLE);
468
469 // we don't have wxVSCROLL style, but the list control may have it,
470 // don't change it then
471 dwStyleNew |= dwStyleOld & (WS_HSCROLL | WS_VSCROLL);
472
473 // Only set the window style if the view bits have changed.
474 if ( dwStyleOld != dwStyleNew )
475 {
476 ::SetWindowLong(GetHwnd(), GWL_STYLE, dwStyleNew);
477
478 // if we switched to the report view, set the extended styles for
479 // it too
480 if ( !(dwStyleOld & LVS_REPORT) && (dwStyleNew & LVS_REPORT) )
481 MSWSetExListStyles();
482 }
483 }
484 }
485
486 void wxListCtrl::FreeAllInternalData()
487 {
488 const unsigned count = m_internalData.size();
489 for ( unsigned n = 0; n < count; n++ )
490 delete m_internalData[n];
491
492 m_internalData.clear();
493 }
494
495 void wxListCtrl::DeleteEditControl()
496 {
497 if ( m_textCtrl )
498 {
499 m_textCtrl->UnsubclassWin();
500 m_textCtrl->SetHWND(0);
501 wxDELETE(m_textCtrl);
502 }
503 }
504
505 wxListCtrl::~wxListCtrl()
506 {
507 FreeAllInternalData();
508
509 DeleteEditControl();
510
511 if (m_ownsImageListNormal)
512 delete m_imageListNormal;
513 if (m_ownsImageListSmall)
514 delete m_imageListSmall;
515 if (m_ownsImageListState)
516 delete m_imageListState;
517 }
518
519 // ----------------------------------------------------------------------------
520 // set/get/change style
521 // ----------------------------------------------------------------------------
522
523 // Add or remove a single window style
524 void wxListCtrl::SetSingleStyle(long style, bool add)
525 {
526 long flag = GetWindowStyleFlag();
527
528 // Get rid of conflicting styles
529 if ( add )
530 {
531 if ( style & wxLC_MASK_TYPE)
532 flag = flag & ~wxLC_MASK_TYPE;
533 if ( style & wxLC_MASK_ALIGN )
534 flag = flag & ~wxLC_MASK_ALIGN;
535 if ( style & wxLC_MASK_SORT )
536 flag = flag & ~wxLC_MASK_SORT;
537 }
538
539 if ( add )
540 flag |= style;
541 else
542 flag &= ~style;
543
544 SetWindowStyleFlag(flag);
545 }
546
547 // Set the whole window style
548 void wxListCtrl::SetWindowStyleFlag(long flag)
549 {
550 if ( flag != m_windowStyle )
551 {
552 wxControl::SetWindowStyleFlag(flag);
553
554 UpdateStyle();
555
556 Refresh();
557 }
558 }
559
560 // ----------------------------------------------------------------------------
561 // accessors
562 // ----------------------------------------------------------------------------
563
564 /* static */ wxVisualAttributes
565 wxListCtrl::GetClassDefaultAttributes(wxWindowVariant variant)
566 {
567 wxVisualAttributes attrs = GetCompositeControlsDefaultAttributes(variant);
568
569 // common controls have their own default font
570 attrs.font = wxGetCCDefaultFont();
571
572 return attrs;
573 }
574
575 // Sets the foreground, i.e. text, colour
576 bool wxListCtrl::SetForegroundColour(const wxColour& col)
577 {
578 if ( !wxWindow::SetForegroundColour(col) )
579 return false;
580
581 ListView_SetTextColor(GetHwnd(), wxColourToRGB(col));
582
583 return true;
584 }
585
586 // Sets the background colour
587 bool wxListCtrl::SetBackgroundColour(const wxColour& col)
588 {
589 if ( !wxWindow::SetBackgroundColour(col) )
590 return false;
591
592 // we set the same colour for both the "empty" background and the items
593 // background
594 COLORREF color = wxColourToRGB(col);
595 ListView_SetBkColor(GetHwnd(), color);
596 ListView_SetTextBkColor(GetHwnd(), color);
597
598 return true;
599 }
600
601 // Gets information about this column
602 bool wxListCtrl::GetColumn(int col, wxListItem& item) const
603 {
604 LV_COLUMN lvCol;
605 wxZeroMemory(lvCol);
606
607 lvCol.mask = LVCF_WIDTH;
608
609 if ( item.m_mask & wxLIST_MASK_TEXT )
610 {
611 lvCol.mask |= LVCF_TEXT;
612 lvCol.pszText = new wxChar[513];
613 lvCol.cchTextMax = 512;
614 }
615
616 if ( item.m_mask & wxLIST_MASK_FORMAT )
617 {
618 lvCol.mask |= LVCF_FMT;
619 }
620
621 if ( item.m_mask & wxLIST_MASK_IMAGE )
622 {
623 lvCol.mask |= LVCF_IMAGE;
624 }
625
626 bool success = ListView_GetColumn(GetHwnd(), col, &lvCol) != 0;
627
628 // item.m_subItem = lvCol.iSubItem;
629 item.m_width = lvCol.cx;
630
631 if ( (item.m_mask & wxLIST_MASK_TEXT) && lvCol.pszText )
632 {
633 item.m_text = lvCol.pszText;
634 delete[] lvCol.pszText;
635 }
636
637 if ( item.m_mask & wxLIST_MASK_FORMAT )
638 {
639 switch (lvCol.fmt & LVCFMT_JUSTIFYMASK) {
640 case LVCFMT_LEFT:
641 item.m_format = wxLIST_FORMAT_LEFT;
642 break;
643 case LVCFMT_RIGHT:
644 item.m_format = wxLIST_FORMAT_RIGHT;
645 break;
646 case LVCFMT_CENTER:
647 item.m_format = wxLIST_FORMAT_CENTRE;
648 break;
649 default:
650 item.m_format = -1; // Unknown?
651 break;
652 }
653 }
654
655 // the column images were not supported in older versions but how to check
656 // for this? we can't use _WIN32_IE because we always define it to a very
657 // high value, so see if another symbol which is only defined starting from
658 // comctl32.dll 4.70 is available
659 #ifdef NM_CUSTOMDRAW // _WIN32_IE >= 0x0300
660 if ( item.m_mask & wxLIST_MASK_IMAGE )
661 {
662 item.m_image = lvCol.iImage;
663 }
664 #endif // LVCOLUMN::iImage exists
665
666 return success;
667 }
668
669 // Sets information about this column
670 bool wxListCtrl::SetColumn(int col, const wxListItem& item)
671 {
672 LV_COLUMN lvCol;
673 wxConvertToMSWListCol(GetHwnd(), col, item, lvCol);
674
675 return ListView_SetColumn(GetHwnd(), col, &lvCol) != 0;
676 }
677
678 // Gets the column width
679 int wxListCtrl::GetColumnWidth(int col) const
680 {
681 return ListView_GetColumnWidth(GetHwnd(), col);
682 }
683
684 // Sets the column width
685 bool wxListCtrl::SetColumnWidth(int col, int width)
686 {
687 if ( m_windowStyle & wxLC_LIST )
688 col = 0;
689
690 if ( width == wxLIST_AUTOSIZE)
691 width = LVSCW_AUTOSIZE;
692 else if ( width == wxLIST_AUTOSIZE_USEHEADER)
693 width = LVSCW_AUTOSIZE_USEHEADER;
694
695 return ListView_SetColumnWidth(GetHwnd(), col, width) != 0;
696 }
697
698 // ----------------------------------------------------------------------------
699 // columns order
700 // ----------------------------------------------------------------------------
701
702 int wxListCtrl::GetColumnIndexFromOrder(int order) const
703 {
704 const int numCols = GetColumnCount();
705 wxCHECK_MSG( order >= 0 && order < numCols, -1,
706 wxT("Column position out of bounds") );
707
708 wxArrayInt indexArray(numCols);
709 if ( !ListView_GetColumnOrderArray(GetHwnd(), numCols, &indexArray[0]) )
710 return -1;
711
712 return indexArray[order];
713 }
714
715 int wxListCtrl::GetColumnOrder(int col) const
716 {
717 const int numCols = GetColumnCount();
718 wxASSERT_MSG( col >= 0 && col < numCols, wxT("Column index out of bounds") );
719
720 wxArrayInt indexArray(numCols);
721 if ( !ListView_GetColumnOrderArray(GetHwnd(), numCols, &indexArray[0]) )
722 return -1;
723
724 for ( int pos = 0; pos < numCols; pos++ )
725 {
726 if ( indexArray[pos] == col )
727 return pos;
728 }
729
730 wxFAIL_MSG( wxT("no column with with given order?") );
731
732 return -1;
733 }
734
735 // Gets the column order for all columns
736 wxArrayInt wxListCtrl::GetColumnsOrder() const
737 {
738 const int numCols = GetColumnCount();
739
740 wxArrayInt orders(numCols);
741 if ( !ListView_GetColumnOrderArray(GetHwnd(), numCols, &orders[0]) )
742 orders.clear();
743
744 return orders;
745 }
746
747 // Sets the column order for all columns
748 bool wxListCtrl::SetColumnsOrder(const wxArrayInt& orders)
749 {
750 const int numCols = GetColumnCount();
751
752 wxCHECK_MSG( orders.size() == (size_t)numCols, false,
753 wxT("wrong number of elements in column orders array") );
754
755 return ListView_SetColumnOrderArray(GetHwnd(), numCols, &orders[0]) != 0;
756 }
757
758
759 // Gets the number of items that can fit vertically in the
760 // visible area of the list control (list or report view)
761 // or the total number of items in the list control (icon
762 // or small icon view)
763 int wxListCtrl::GetCountPerPage() const
764 {
765 return ListView_GetCountPerPage(GetHwnd());
766 }
767
768 // Gets the edit control for editing labels.
769 wxTextCtrl* wxListCtrl::GetEditControl() const
770 {
771 // first check corresponds to the case when the label editing was started
772 // by user and hence m_textCtrl wasn't created by EditLabel() at all, while
773 // the second case corresponds to us being called from inside EditLabel()
774 // (e.g. from a user wxEVT_COMMAND_LIST_BEGIN_LABEL_EDIT handler): in this
775 // case EditLabel() did create the control but it didn't have an HWND to
776 // initialize it with yet
777 if ( !m_textCtrl || !m_textCtrl->GetHWND() )
778 {
779 HWND hwndEdit = ListView_GetEditControl(GetHwnd());
780 if ( hwndEdit )
781 {
782 wxListCtrl * const self = const_cast<wxListCtrl *>(this);
783
784 if ( !m_textCtrl )
785 self->m_textCtrl = new wxTextCtrl;
786 self->InitEditControl((WXHWND)hwndEdit);
787 }
788 }
789
790 return m_textCtrl;
791 }
792
793 // Gets information about the item
794 bool wxListCtrl::GetItem(wxListItem& info) const
795 {
796 LV_ITEM lvItem;
797 wxZeroMemory(lvItem);
798
799 lvItem.iItem = info.m_itemId;
800 lvItem.iSubItem = info.m_col;
801
802 if ( info.m_mask & wxLIST_MASK_TEXT )
803 {
804 lvItem.mask |= LVIF_TEXT;
805 lvItem.pszText = new wxChar[513];
806 lvItem.cchTextMax = 512;
807 }
808 else
809 {
810 lvItem.pszText = NULL;
811 }
812
813 if (info.m_mask & wxLIST_MASK_DATA)
814 lvItem.mask |= LVIF_PARAM;
815
816 if (info.m_mask & wxLIST_MASK_IMAGE)
817 lvItem.mask |= LVIF_IMAGE;
818
819 if ( info.m_mask & wxLIST_MASK_STATE )
820 {
821 lvItem.mask |= LVIF_STATE;
822 wxConvertToMSWFlags(0, info.m_stateMask, lvItem);
823 }
824
825 bool success = ListView_GetItem((HWND)GetHWND(), &lvItem) != 0;
826 if ( !success )
827 {
828 wxLogError(_("Couldn't retrieve information about list control item %d."),
829 lvItem.iItem);
830 }
831 else
832 {
833 // give NULL as hwnd as we already have everything we need
834 wxConvertFromMSWListItem(NULL, info, lvItem);
835 }
836
837 if (lvItem.pszText)
838 delete[] lvItem.pszText;
839
840 return success;
841 }
842
843 // Sets information about the item
844 bool wxListCtrl::SetItem(wxListItem& info)
845 {
846 const long id = info.GetId();
847 wxCHECK_MSG( id >= 0 && id < GetItemCount(), false,
848 wxT("invalid item index in SetItem") );
849
850 LV_ITEM item;
851 wxConvertToMSWListItem(this, info, item);
852
853 // we never update the lParam if it contains our pointer
854 // to the wxMSWListItemData structure
855 item.mask &= ~LVIF_PARAM;
856
857 // check if setting attributes or lParam
858 if ( info.HasAttributes() || (info.m_mask & wxLIST_MASK_DATA) )
859 {
860 // get internal item data
861 wxMSWListItemData *data = MSWGetItemData(id);
862
863 if ( !data )
864 {
865 // need to allocate the internal data object
866 data = new wxMSWListItemData;
867 m_internalData.push_back(data);
868 item.lParam = (LPARAM) data;
869 item.mask |= LVIF_PARAM;
870 }
871
872
873 // user data
874 if ( info.m_mask & wxLIST_MASK_DATA )
875 data->lParam = info.m_data;
876
877 // attributes
878 if ( info.HasAttributes() )
879 {
880 const wxListItemAttr& attrNew = *info.GetAttributes();
881
882 // don't overwrite the already set attributes if we have them
883 if ( data->attr )
884 data->attr->AssignFrom(attrNew);
885 else
886 data->attr = new wxListItemAttr(attrNew);
887 }
888 }
889
890
891 // we could be changing only the attribute in which case we don't need to
892 // call ListView_SetItem() at all
893 if ( item.mask )
894 {
895 if ( !ListView_SetItem(GetHwnd(), &item) )
896 {
897 wxLogDebug(wxT("ListView_SetItem() failed"));
898
899 return false;
900 }
901 }
902
903 // we need to update the item immediately to show the new image
904 bool updateNow = (info.m_mask & wxLIST_MASK_IMAGE) != 0;
905
906 // check whether it has any custom attributes
907 if ( info.HasAttributes() )
908 {
909 m_hasAnyAttr = true;
910
911 // if the colour has changed, we must redraw the item
912 updateNow = true;
913 }
914
915 if ( updateNow )
916 {
917 // we need this to make the change visible right now
918 RefreshItem(item.iItem);
919 }
920
921 return true;
922 }
923
924 long wxListCtrl::SetItem(long index, int col, const wxString& label, int imageId)
925 {
926 wxListItem info;
927 info.m_text = label;
928 info.m_mask = wxLIST_MASK_TEXT;
929 info.m_itemId = index;
930 info.m_col = col;
931 if ( imageId > -1 )
932 {
933 info.m_image = imageId;
934 info.m_mask |= wxLIST_MASK_IMAGE;
935 }
936 return SetItem(info);
937 }
938
939
940 // Gets the item state
941 int wxListCtrl::GetItemState(long item, long stateMask) const
942 {
943 wxListItem info;
944
945 info.m_mask = wxLIST_MASK_STATE;
946 info.m_stateMask = stateMask;
947 info.m_itemId = item;
948
949 if (!GetItem(info))
950 return 0;
951
952 return info.m_state;
953 }
954
955 // Sets the item state
956 bool wxListCtrl::SetItemState(long item, long state, long stateMask)
957 {
958 // NB: don't use SetItem() here as it doesn't work with the virtual list
959 // controls
960 LV_ITEM lvItem;
961 wxZeroMemory(lvItem);
962
963 wxConvertToMSWFlags(state, stateMask, lvItem);
964
965 const bool changingFocus = (stateMask & wxLIST_STATE_FOCUSED) &&
966 (state & wxLIST_STATE_FOCUSED);
967
968 // for the virtual list controls we need to refresh the previously focused
969 // item manually when changing focus without changing selection
970 // programmatically because otherwise it keeps its focus rectangle until
971 // next repaint (yet another comctl32 bug)
972 long focusOld;
973 if ( IsVirtual() && changingFocus )
974 {
975 focusOld = GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_FOCUSED);
976 }
977 else
978 {
979 focusOld = -1;
980 }
981
982 if ( !::SendMessage(GetHwnd(), LVM_SETITEMSTATE,
983 (WPARAM)item, (LPARAM)&lvItem) )
984 {
985 wxLogLastError(wxT("ListView_SetItemState"));
986
987 return false;
988 }
989
990 if ( focusOld != -1 )
991 {
992 // no need to refresh the item if it was previously selected, it would
993 // only result in annoying flicker
994 if ( !(GetItemState(focusOld,
995 wxLIST_STATE_SELECTED) & wxLIST_STATE_SELECTED) )
996 {
997 RefreshItem(focusOld);
998 }
999 }
1000
1001 // we expect the selection anchor, i.e. the item from which multiple
1002 // selection (such as performed with e.g. Shift-arrows) starts, to be the
1003 // same as the currently focused item but the native control doesn't update
1004 // it when we change focus and leaves at the last item it set itself focus
1005 // to, so do it explicitly
1006 if ( changingFocus && !HasFlag(wxLC_SINGLE_SEL) )
1007 {
1008 ListView_SetSelectionMark(GetHwnd(), item);
1009 }
1010
1011 return true;
1012 }
1013
1014 // Sets the item image
1015 bool wxListCtrl::SetItemImage(long item, int image, int WXUNUSED(selImage))
1016 {
1017 return SetItemColumnImage(item, 0, image);
1018 }
1019
1020 // Sets the item image
1021 bool wxListCtrl::SetItemColumnImage(long item, long column, int image)
1022 {
1023 wxListItem info;
1024
1025 info.m_mask = wxLIST_MASK_IMAGE;
1026 info.m_image = image;
1027 info.m_itemId = item;
1028 info.m_col = column;
1029
1030 return SetItem(info);
1031 }
1032
1033 // Gets the item text
1034 wxString wxListCtrl::GetItemText(long item, int col) const
1035 {
1036 wxListItem info;
1037
1038 info.m_mask = wxLIST_MASK_TEXT;
1039 info.m_itemId = item;
1040 info.m_col = col;
1041
1042 if (!GetItem(info))
1043 return wxEmptyString;
1044 return info.m_text;
1045 }
1046
1047 // Sets the item text
1048 void wxListCtrl::SetItemText(long item, const wxString& str)
1049 {
1050 wxListItem info;
1051
1052 info.m_mask = wxLIST_MASK_TEXT;
1053 info.m_itemId = item;
1054 info.m_text = str;
1055
1056 SetItem(info);
1057 }
1058
1059 // Gets the internal item data
1060 wxMSWListItemData *wxListCtrl::MSWGetItemData(long itemId) const
1061 {
1062 LV_ITEM it;
1063 it.mask = LVIF_PARAM;
1064 it.iItem = itemId;
1065
1066 if ( !ListView_GetItem(GetHwnd(), &it) )
1067 return NULL;
1068
1069 return (wxMSWListItemData *) it.lParam;
1070 }
1071
1072 // Gets the item data
1073 wxUIntPtr wxListCtrl::GetItemData(long item) const
1074 {
1075 wxListItem info;
1076
1077 info.m_mask = wxLIST_MASK_DATA;
1078 info.m_itemId = item;
1079
1080 if (!GetItem(info))
1081 return 0;
1082 return info.m_data;
1083 }
1084
1085 // Sets the item data
1086 bool wxListCtrl::SetItemPtrData(long item, wxUIntPtr data)
1087 {
1088 wxListItem info;
1089
1090 info.m_mask = wxLIST_MASK_DATA;
1091 info.m_itemId = item;
1092 info.m_data = data;
1093
1094 return SetItem(info);
1095 }
1096
1097 wxRect wxListCtrl::GetViewRect() const
1098 {
1099 wxRect rect;
1100
1101 // ListView_GetViewRect() can only be used in icon and small icon views
1102 // (this is documented in MSDN and, indeed, it returns bogus results in
1103 // report view, at least with comctl32.dll v6 under Windows 2003)
1104 if ( HasFlag(wxLC_ICON | wxLC_SMALL_ICON) )
1105 {
1106 RECT rc;
1107 if ( !ListView_GetViewRect(GetHwnd(), &rc) )
1108 {
1109 wxLogDebug(wxT("ListView_GetViewRect() failed."));
1110
1111 wxZeroMemory(rc);
1112 }
1113
1114 wxCopyRECTToRect(rc, rect);
1115 }
1116 else if ( HasFlag(wxLC_REPORT) )
1117 {
1118 const long count = GetItemCount();
1119 if ( count )
1120 {
1121 GetItemRect(wxMin(GetTopItem() + GetCountPerPage(), count - 1), rect);
1122
1123 // extend the rectangle to start at the top (we include the column
1124 // headers, if any, for compatibility with the generic version)
1125 rect.height += rect.y;
1126 rect.y = 0;
1127 }
1128 }
1129 else
1130 {
1131 wxFAIL_MSG( wxT("not implemented in this mode") );
1132 }
1133
1134 return rect;
1135 }
1136
1137 // Gets the item rectangle
1138 bool wxListCtrl::GetItemRect(long item, wxRect& rect, int code) const
1139 {
1140 return GetSubItemRect( item, wxLIST_GETSUBITEMRECT_WHOLEITEM, rect, code) ;
1141 }
1142
1143 bool wxListCtrl::GetSubItemRect(long item, long subItem, wxRect& rect, int code) const
1144 {
1145 // ListView_GetSubItemRect() doesn't do subItem error checking and returns
1146 // true even for the out of range values of it (even if the results are
1147 // completely bogus in this case), so we check item validity ourselves
1148 wxCHECK_MSG( subItem == wxLIST_GETSUBITEMRECT_WHOLEITEM ||
1149 (subItem >= 0 && subItem < GetColumnCount()),
1150 false, wxT("invalid sub item index") );
1151
1152 // use wxCHECK_MSG against "item" too, for coherency with the generic implementation:
1153 wxCHECK_MSG( item >= 0 && item < GetItemCount(), false,
1154 wxT("invalid item in GetSubItemRect") );
1155
1156 int codeWin;
1157 if ( code == wxLIST_RECT_BOUNDS )
1158 codeWin = LVIR_BOUNDS;
1159 else if ( code == wxLIST_RECT_ICON )
1160 codeWin = LVIR_ICON;
1161 else if ( code == wxLIST_RECT_LABEL )
1162 codeWin = LVIR_LABEL;
1163 else
1164 {
1165 wxFAIL_MSG( wxT("incorrect code in GetItemRect() / GetSubItemRect()") );
1166 codeWin = LVIR_BOUNDS;
1167 }
1168
1169 RECT rectWin;
1170 if ( !wxGetListCtrlSubItemRect
1171 (
1172 GetHwnd(),
1173 item,
1174 subItem == wxLIST_GETSUBITEMRECT_WHOLEITEM ? 0 : subItem,
1175 codeWin,
1176 rectWin
1177 ) )
1178 {
1179 return false;
1180 }
1181
1182 wxCopyRECTToRect(rectWin, rect);
1183
1184 // there is no way to retrieve the first sub item bounding rectangle using
1185 // wxGetListCtrlSubItemRect() as 0 means the whole item, so we need to
1186 // truncate it at first column ourselves
1187 if ( subItem == 0 && code == wxLIST_RECT_BOUNDS )
1188 rect.width = GetColumnWidth(0);
1189
1190 return true;
1191 }
1192
1193
1194
1195
1196 // Gets the item position
1197 bool wxListCtrl::GetItemPosition(long item, wxPoint& pos) const
1198 {
1199 POINT pt;
1200
1201 bool success = (ListView_GetItemPosition(GetHwnd(), (int) item, &pt) != 0);
1202
1203 pos.x = pt.x; pos.y = pt.y;
1204 return success;
1205 }
1206
1207 // Sets the item position.
1208 bool wxListCtrl::SetItemPosition(long item, const wxPoint& pos)
1209 {
1210 return (ListView_SetItemPosition(GetHwnd(), (int) item, pos.x, pos.y) != 0);
1211 }
1212
1213 // Gets the number of items in the list control
1214 int wxListCtrl::GetItemCount() const
1215 {
1216 return m_count;
1217 }
1218
1219 wxSize wxListCtrl::GetItemSpacing() const
1220 {
1221 const int spacing = ListView_GetItemSpacing(GetHwnd(), (BOOL)HasFlag(wxLC_SMALL_ICON));
1222
1223 return wxSize(LOWORD(spacing), HIWORD(spacing));
1224 }
1225
1226 #if WXWIN_COMPATIBILITY_2_6
1227
1228 int wxListCtrl::GetItemSpacing(bool isSmall) const
1229 {
1230 return ListView_GetItemSpacing(GetHwnd(), (BOOL) isSmall);
1231 }
1232
1233 #endif // WXWIN_COMPATIBILITY_2_6
1234
1235 void wxListCtrl::SetItemTextColour( long item, const wxColour &col )
1236 {
1237 wxListItem info;
1238 info.m_itemId = item;
1239 info.SetTextColour( col );
1240 SetItem( info );
1241 }
1242
1243 wxColour wxListCtrl::GetItemTextColour( long item ) const
1244 {
1245 wxColour col;
1246 wxMSWListItemData *data = MSWGetItemData(item);
1247 if ( data && data->attr )
1248 col = data->attr->GetTextColour();
1249
1250 return col;
1251 }
1252
1253 void wxListCtrl::SetItemBackgroundColour( long item, const wxColour &col )
1254 {
1255 wxListItem info;
1256 info.m_itemId = item;
1257 info.SetBackgroundColour( col );
1258 SetItem( info );
1259 }
1260
1261 wxColour wxListCtrl::GetItemBackgroundColour( long item ) const
1262 {
1263 wxColour col;
1264 wxMSWListItemData *data = MSWGetItemData(item);
1265 if ( data && data->attr )
1266 col = data->attr->GetBackgroundColour();
1267
1268 return col;
1269 }
1270
1271 void wxListCtrl::SetItemFont( long item, const wxFont &f )
1272 {
1273 wxListItem info;
1274 info.m_itemId = item;
1275 info.SetFont( f );
1276 SetItem( info );
1277 }
1278
1279 wxFont wxListCtrl::GetItemFont( long item ) const
1280 {
1281 wxFont f;
1282 wxMSWListItemData *data = MSWGetItemData(item);
1283 if ( data && data->attr )
1284 f = data->attr->GetFont();
1285
1286 return f;
1287 }
1288
1289 // Gets the number of selected items in the list control
1290 int wxListCtrl::GetSelectedItemCount() const
1291 {
1292 return ListView_GetSelectedCount(GetHwnd());
1293 }
1294
1295 // Gets the text colour of the listview
1296 wxColour wxListCtrl::GetTextColour() const
1297 {
1298 COLORREF ref = ListView_GetTextColor(GetHwnd());
1299 wxColour col(GetRValue(ref), GetGValue(ref), GetBValue(ref));
1300 return col;
1301 }
1302
1303 // Sets the text colour of the listview
1304 void wxListCtrl::SetTextColour(const wxColour& col)
1305 {
1306 ListView_SetTextColor(GetHwnd(), PALETTERGB(col.Red(), col.Green(), col.Blue()));
1307 }
1308
1309 // Gets the index of the topmost visible item when in
1310 // list or report view
1311 long wxListCtrl::GetTopItem() const
1312 {
1313 return (long) ListView_GetTopIndex(GetHwnd());
1314 }
1315
1316 // Searches for an item, starting from 'item'.
1317 // 'geometry' is one of
1318 // wxLIST_NEXT_ABOVE/ALL/BELOW/LEFT/RIGHT.
1319 // 'state' is a state bit flag, one or more of
1320 // wxLIST_STATE_DROPHILITED/FOCUSED/SELECTED/CUT.
1321 // item can be -1 to find the first item that matches the
1322 // specified flags.
1323 // Returns the item or -1 if unsuccessful.
1324 long wxListCtrl::GetNextItem(long item, int geom, int state) const
1325 {
1326 long flags = 0;
1327
1328 if ( geom == wxLIST_NEXT_ABOVE )
1329 flags |= LVNI_ABOVE;
1330 if ( geom == wxLIST_NEXT_ALL )
1331 flags |= LVNI_ALL;
1332 if ( geom == wxLIST_NEXT_BELOW )
1333 flags |= LVNI_BELOW;
1334 if ( geom == wxLIST_NEXT_LEFT )
1335 flags |= LVNI_TOLEFT;
1336 if ( geom == wxLIST_NEXT_RIGHT )
1337 flags |= LVNI_TORIGHT;
1338
1339 if ( state & wxLIST_STATE_CUT )
1340 flags |= LVNI_CUT;
1341 if ( state & wxLIST_STATE_DROPHILITED )
1342 flags |= LVNI_DROPHILITED;
1343 if ( state & wxLIST_STATE_FOCUSED )
1344 flags |= LVNI_FOCUSED;
1345 if ( state & wxLIST_STATE_SELECTED )
1346 flags |= LVNI_SELECTED;
1347
1348 return (long) ListView_GetNextItem(GetHwnd(), item, flags);
1349 }
1350
1351
1352 wxImageList *wxListCtrl::GetImageList(int which) const
1353 {
1354 if ( which == wxIMAGE_LIST_NORMAL )
1355 {
1356 return m_imageListNormal;
1357 }
1358 else if ( which == wxIMAGE_LIST_SMALL )
1359 {
1360 return m_imageListSmall;
1361 }
1362 else if ( which == wxIMAGE_LIST_STATE )
1363 {
1364 return m_imageListState;
1365 }
1366 return NULL;
1367 }
1368
1369 void wxListCtrl::SetImageList(wxImageList *imageList, int which)
1370 {
1371 int flags = 0;
1372 if ( which == wxIMAGE_LIST_NORMAL )
1373 {
1374 flags = LVSIL_NORMAL;
1375 if (m_ownsImageListNormal) delete m_imageListNormal;
1376 m_imageListNormal = imageList;
1377 m_ownsImageListNormal = false;
1378 }
1379 else if ( which == wxIMAGE_LIST_SMALL )
1380 {
1381 flags = LVSIL_SMALL;
1382 if (m_ownsImageListSmall) delete m_imageListSmall;
1383 m_imageListSmall = imageList;
1384 m_ownsImageListSmall = false;
1385 }
1386 else if ( which == wxIMAGE_LIST_STATE )
1387 {
1388 flags = LVSIL_STATE;
1389 if (m_ownsImageListState) delete m_imageListState;
1390 m_imageListState = imageList;
1391 m_ownsImageListState = false;
1392 }
1393 (void) ListView_SetImageList(GetHwnd(), (HIMAGELIST) imageList ? imageList->GetHIMAGELIST() : 0, flags);
1394 }
1395
1396 void wxListCtrl::AssignImageList(wxImageList *imageList, int which)
1397 {
1398 SetImageList(imageList, which);
1399 if ( which == wxIMAGE_LIST_NORMAL )
1400 m_ownsImageListNormal = true;
1401 else if ( which == wxIMAGE_LIST_SMALL )
1402 m_ownsImageListSmall = true;
1403 else if ( which == wxIMAGE_LIST_STATE )
1404 m_ownsImageListState = true;
1405 }
1406
1407 // ----------------------------------------------------------------------------
1408 // Operations
1409 // ----------------------------------------------------------------------------
1410
1411 // Arranges the items
1412 bool wxListCtrl::Arrange(int flag)
1413 {
1414 UINT code = 0;
1415 if ( flag == wxLIST_ALIGN_LEFT )
1416 code = LVA_ALIGNLEFT;
1417 else if ( flag == wxLIST_ALIGN_TOP )
1418 code = LVA_ALIGNTOP;
1419 else if ( flag == wxLIST_ALIGN_DEFAULT )
1420 code = LVA_DEFAULT;
1421 else if ( flag == wxLIST_ALIGN_SNAP_TO_GRID )
1422 code = LVA_SNAPTOGRID;
1423
1424 return (ListView_Arrange(GetHwnd(), code) != 0);
1425 }
1426
1427 // Deletes an item
1428 bool wxListCtrl::DeleteItem(long item)
1429 {
1430 if ( !ListView_DeleteItem(GetHwnd(), (int) item) )
1431 {
1432 wxLogLastError(wxT("ListView_DeleteItem"));
1433 return false;
1434 }
1435
1436 m_count--;
1437 wxASSERT_MSG( m_count == ListView_GetItemCount(GetHwnd()),
1438 wxT("m_count should match ListView_GetItemCount"));
1439
1440 // the virtual list control doesn't refresh itself correctly, help it
1441 if ( IsVirtual() )
1442 {
1443 // we need to refresh all the lines below the one which was deleted
1444 wxRect rectItem;
1445 if ( item > 0 && GetItemCount() )
1446 {
1447 GetItemRect(item - 1, rectItem);
1448 }
1449 else
1450 {
1451 rectItem.y =
1452 rectItem.height = 0;
1453 }
1454
1455 wxRect rectWin = GetRect();
1456 rectWin.height = rectWin.GetBottom() - rectItem.GetBottom();
1457 rectWin.y = rectItem.GetBottom();
1458
1459 RefreshRect(rectWin);
1460 }
1461
1462 return true;
1463 }
1464
1465 // Deletes all items
1466 bool wxListCtrl::DeleteAllItems()
1467 {
1468 // Calling ListView_DeleteAllItems() will always generate an event but we
1469 // shouldn't do it if the control is empty
1470 return !GetItemCount() || ListView_DeleteAllItems(GetHwnd()) != 0;
1471 }
1472
1473 // Deletes all items
1474 bool wxListCtrl::DeleteAllColumns()
1475 {
1476 while ( m_colCount > 0 )
1477 {
1478 if ( ListView_DeleteColumn(GetHwnd(), 0) == 0 )
1479 {
1480 wxLogLastError(wxT("ListView_DeleteColumn"));
1481
1482 return false;
1483 }
1484
1485 m_colCount--;
1486 }
1487
1488 wxASSERT_MSG( m_colCount == 0, wxT("no columns should be left") );
1489
1490 return true;
1491 }
1492
1493 // Deletes a column
1494 bool wxListCtrl::DeleteColumn(int col)
1495 {
1496 bool success = (ListView_DeleteColumn(GetHwnd(), col) != 0);
1497
1498 if ( success && (m_colCount > 0) )
1499 m_colCount --;
1500 return success;
1501 }
1502
1503 // Clears items, and columns if there are any.
1504 void wxListCtrl::ClearAll()
1505 {
1506 DeleteAllItems();
1507 if ( m_colCount > 0 )
1508 DeleteAllColumns();
1509 }
1510
1511 void wxListCtrl::InitEditControl(WXHWND hWnd)
1512 {
1513 m_textCtrl->SetHWND(hWnd);
1514 m_textCtrl->SubclassWin(hWnd);
1515 m_textCtrl->SetParent(this);
1516
1517 // we must disallow TABbing away from the control while the edit contol is
1518 // shown because this leaves it in some strange state (just try removing
1519 // this line and then pressing TAB while editing an item in listctrl
1520 // inside a panel)
1521 m_textCtrl->SetWindowStyle(m_textCtrl->GetWindowStyle() | wxTE_PROCESS_TAB);
1522 }
1523
1524 wxTextCtrl* wxListCtrl::EditLabel(long item, wxClassInfo* textControlClass)
1525 {
1526 wxCHECK_MSG( textControlClass->IsKindOf(CLASSINFO(wxTextCtrl)), NULL,
1527 "control used for label editing must be a wxTextCtrl" );
1528
1529 // ListView_EditLabel requires that the list has focus.
1530 SetFocus();
1531
1532 // create m_textCtrl here before calling ListView_EditLabel() because it
1533 // generates wxEVT_COMMAND_LIST_BEGIN_LABEL_EDIT event from inside it and
1534 // the user handler for it can call GetEditControl() resulting in an on
1535 // demand creation of a stock wxTextCtrl instead of the control of a
1536 // (possibly) custom wxClassInfo
1537 DeleteEditControl();
1538 m_textCtrl = (wxTextCtrl *)textControlClass->CreateObject();
1539
1540 WXHWND hWnd = (WXHWND) ListView_EditLabel(GetHwnd(), item);
1541 if ( !hWnd )
1542 {
1543 // failed to start editing
1544 wxDELETE(m_textCtrl);
1545
1546 return NULL;
1547 }
1548
1549 // if GetEditControl() hasn't been called, we need to initialize the edit
1550 // control ourselves
1551 if ( !m_textCtrl->GetHWND() )
1552 InitEditControl(hWnd);
1553
1554 return m_textCtrl;
1555 }
1556
1557 // End label editing, optionally cancelling the edit
1558 bool wxListCtrl::EndEditLabel(bool cancel)
1559 {
1560 // m_textCtrl is not always ready, ie. in EVT_LIST_BEGIN_LABEL_EDIT
1561 HWND hwnd = ListView_GetEditControl(GetHwnd());
1562 if ( !hwnd )
1563 return false;
1564
1565 // Newer versions of Windows have a special message for cancelling editing,
1566 // use it if available.
1567 #ifdef ListView_CancelEditLabel
1568 if ( cancel && (wxApp::GetComCtl32Version() >= 600) )
1569 {
1570 ListView_CancelEditLabel(GetHwnd());
1571 }
1572 else
1573 #endif // ListView_CancelEditLabel
1574 {
1575 // We shouldn't destroy the control ourselves according to MSDN, which
1576 // proposes WM_CANCELMODE to do this, but it doesn't seem to work so
1577 // emulate the corresponding user action instead.
1578 ::SendMessage(hwnd, WM_KEYDOWN, cancel ? VK_ESCAPE : VK_RETURN, 0);
1579 }
1580
1581 return true;
1582 }
1583
1584 // Ensures this item is visible
1585 bool wxListCtrl::EnsureVisible(long item)
1586 {
1587 return ListView_EnsureVisible(GetHwnd(), (int) item, FALSE) != FALSE;
1588 }
1589
1590 // Find an item whose label matches this string, starting from the item after 'start'
1591 // or the beginning if 'start' is -1.
1592 long wxListCtrl::FindItem(long start, const wxString& str, bool partial)
1593 {
1594 LV_FINDINFO findInfo;
1595
1596 findInfo.flags = LVFI_STRING;
1597 if ( partial )
1598 findInfo.flags |= LVFI_PARTIAL;
1599 findInfo.psz = str.wx_str();
1600
1601 // ListView_FindItem() excludes the first item from search and to look
1602 // through all the items you need to start from -1 which is unnatural and
1603 // inconsistent with the generic version - so we adjust the index
1604 if (start != -1)
1605 start --;
1606 return ListView_FindItem(GetHwnd(), start, &findInfo);
1607 }
1608
1609 // Find an item whose data matches this data, starting from the item after
1610 // 'start' or the beginning if 'start' is -1.
1611 long wxListCtrl::FindItem(long start, wxUIntPtr data)
1612 {
1613 // we can't use ListView_FindItem() directly as we don't store the data
1614 // pointer itself in the control but rather our own internal data, so first
1615 // we need to find the right value to search for (and there can be several
1616 // of them)
1617 int idx = wxNOT_FOUND;
1618 const unsigned count = m_internalData.size();
1619 for ( unsigned n = 0; n < count; n++ )
1620 {
1621 if ( m_internalData[n]->lParam == (LPARAM)data )
1622 {
1623 LV_FINDINFO findInfo;
1624 findInfo.flags = LVFI_PARAM;
1625 findInfo.lParam = (LPARAM)wxPtrToUInt(m_internalData[n]);
1626
1627 int rc = ListView_FindItem(GetHwnd(), start, &findInfo);
1628 if ( rc != -1 )
1629 {
1630 if ( idx == wxNOT_FOUND || rc < idx )
1631 {
1632 idx = rc;
1633 if ( idx == start + 1 )
1634 {
1635 // we can stop here, we don't risk finding a closer
1636 // match
1637 break;
1638 }
1639 }
1640 //else: this item is after the previously found one
1641 }
1642 }
1643 }
1644
1645 return idx;
1646 }
1647
1648 // Find an item nearest this position in the specified direction, starting from
1649 // the item after 'start' or the beginning if 'start' is -1.
1650 long wxListCtrl::FindItem(long start, const wxPoint& pt, int direction)
1651 {
1652 LV_FINDINFO findInfo;
1653
1654 findInfo.flags = LVFI_NEARESTXY;
1655 findInfo.pt.x = pt.x;
1656 findInfo.pt.y = pt.y;
1657 findInfo.vkDirection = VK_RIGHT;
1658
1659 if ( direction == wxLIST_FIND_UP )
1660 findInfo.vkDirection = VK_UP;
1661 else if ( direction == wxLIST_FIND_DOWN )
1662 findInfo.vkDirection = VK_DOWN;
1663 else if ( direction == wxLIST_FIND_LEFT )
1664 findInfo.vkDirection = VK_LEFT;
1665 else if ( direction == wxLIST_FIND_RIGHT )
1666 findInfo.vkDirection = VK_RIGHT;
1667
1668 return ListView_FindItem(GetHwnd(), start, &findInfo);
1669 }
1670
1671 // Determines which item (if any) is at the specified point,
1672 // giving details in 'flags' (see wxLIST_HITTEST_... flags above)
1673 long
1674 wxListCtrl::HitTest(const wxPoint& point, int& flags, long *ptrSubItem) const
1675 {
1676 LV_HITTESTINFO hitTestInfo;
1677 hitTestInfo.pt.x = (int) point.x;
1678 hitTestInfo.pt.y = (int) point.y;
1679
1680 long item;
1681 #ifdef LVM_SUBITEMHITTEST
1682 if ( ptrSubItem && wxApp::GetComCtl32Version() >= 470 )
1683 {
1684 item = ListView_SubItemHitTest(GetHwnd(), &hitTestInfo);
1685 *ptrSubItem = hitTestInfo.iSubItem;
1686 }
1687 else
1688 #endif // LVM_SUBITEMHITTEST
1689 {
1690 item = ListView_HitTest(GetHwnd(), &hitTestInfo);
1691 }
1692
1693 flags = 0;
1694
1695 if ( hitTestInfo.flags & LVHT_ABOVE )
1696 flags |= wxLIST_HITTEST_ABOVE;
1697 if ( hitTestInfo.flags & LVHT_BELOW )
1698 flags |= wxLIST_HITTEST_BELOW;
1699 if ( hitTestInfo.flags & LVHT_TOLEFT )
1700 flags |= wxLIST_HITTEST_TOLEFT;
1701 if ( hitTestInfo.flags & LVHT_TORIGHT )
1702 flags |= wxLIST_HITTEST_TORIGHT;
1703
1704 if ( hitTestInfo.flags & LVHT_NOWHERE )
1705 flags |= wxLIST_HITTEST_NOWHERE;
1706
1707 // note a bug or at least a very strange feature of comtl32.dll (tested
1708 // with version 4.0 under Win95 and 6.0 under Win 2003): if you click to
1709 // the right of the item label, ListView_HitTest() returns a combination of
1710 // LVHT_ONITEMICON, LVHT_ONITEMLABEL and LVHT_ONITEMSTATEICON -- filter out
1711 // the bits which don't make sense
1712 if ( hitTestInfo.flags & LVHT_ONITEMLABEL )
1713 {
1714 flags |= wxLIST_HITTEST_ONITEMLABEL;
1715
1716 // do not translate LVHT_ONITEMICON here, as per above
1717 }
1718 else
1719 {
1720 if ( hitTestInfo.flags & LVHT_ONITEMICON )
1721 flags |= wxLIST_HITTEST_ONITEMICON;
1722 if ( hitTestInfo.flags & LVHT_ONITEMSTATEICON )
1723 flags |= wxLIST_HITTEST_ONITEMSTATEICON;
1724 }
1725
1726 return item;
1727 }
1728
1729
1730 // Inserts an item, returning the index of the new item if successful,
1731 // -1 otherwise.
1732 long wxListCtrl::InsertItem(const wxListItem& info)
1733 {
1734 wxASSERT_MSG( !IsVirtual(), wxT("can't be used with virtual controls") );
1735
1736 LV_ITEM item;
1737 wxConvertToMSWListItem(this, info, item);
1738 item.mask &= ~LVIF_PARAM;
1739
1740 // check whether we need to allocate our internal data
1741 bool needInternalData = (info.m_mask & wxLIST_MASK_DATA) ||
1742 info.HasAttributes();
1743 if ( needInternalData )
1744 {
1745 item.mask |= LVIF_PARAM;
1746
1747 wxMSWListItemData * const data = new wxMSWListItemData;
1748 m_internalData.push_back(data);
1749 item.lParam = (LPARAM)data;
1750
1751 if ( info.m_mask & wxLIST_MASK_DATA )
1752 data->lParam = info.m_data;
1753
1754 // check whether it has any custom attributes
1755 if ( info.HasAttributes() )
1756 {
1757 // take copy of attributes
1758 data->attr = new wxListItemAttr(*info.GetAttributes());
1759
1760 // and remember that we have some now...
1761 m_hasAnyAttr = true;
1762 }
1763 }
1764
1765 const long rv = ListView_InsertItem(GetHwnd(), & item);
1766
1767 // failing to insert the item is really unexpected
1768 wxCHECK_MSG( rv != -1, rv, "failed to insert an item in wxListCtrl" );
1769
1770 m_count++;
1771 wxASSERT_MSG( m_count == ListView_GetItemCount(GetHwnd()),
1772 wxT("m_count should match ListView_GetItemCount"));
1773
1774 return rv;
1775 }
1776
1777 long wxListCtrl::InsertItem(long index, const wxString& label)
1778 {
1779 wxListItem info;
1780 info.m_text = label;
1781 info.m_mask = wxLIST_MASK_TEXT;
1782 info.m_itemId = index;
1783 return InsertItem(info);
1784 }
1785
1786 // Inserts an image item
1787 long wxListCtrl::InsertItem(long index, int imageIndex)
1788 {
1789 wxListItem info;
1790 info.m_image = imageIndex;
1791 info.m_mask = wxLIST_MASK_IMAGE;
1792 info.m_itemId = index;
1793 return InsertItem(info);
1794 }
1795
1796 // Inserts an image/string item
1797 long wxListCtrl::InsertItem(long index, const wxString& label, int imageIndex)
1798 {
1799 wxListItem info;
1800 info.m_image = imageIndex;
1801 info.m_text = label;
1802 info.m_mask = wxLIST_MASK_IMAGE | wxLIST_MASK_TEXT;
1803 info.m_itemId = index;
1804 return InsertItem(info);
1805 }
1806
1807 // For list view mode (only), inserts a column.
1808 long wxListCtrl::InsertColumn(long col, const wxListItem& item)
1809 {
1810 LV_COLUMN lvCol;
1811 wxConvertToMSWListCol(GetHwnd(), col, item, lvCol);
1812
1813 if ( !(lvCol.mask & LVCF_WIDTH) )
1814 {
1815 // always give some width to the new column: this one is compatible
1816 // with the generic version
1817 lvCol.mask |= LVCF_WIDTH;
1818 lvCol.cx = 80;
1819 }
1820
1821 long n = ListView_InsertColumn(GetHwnd(), col, &lvCol);
1822 if ( n != -1 )
1823 {
1824 m_colCount++;
1825 }
1826 else // failed to insert?
1827 {
1828 wxLogDebug(wxT("Failed to insert the column '%s' into listview!"),
1829 lvCol.pszText);
1830 }
1831
1832 return n;
1833 }
1834
1835 long wxListCtrl::InsertColumn(long col,
1836 const wxString& heading,
1837 int format,
1838 int width)
1839 {
1840 wxListItem item;
1841 item.m_mask = wxLIST_MASK_TEXT | wxLIST_MASK_FORMAT;
1842 item.m_text = heading;
1843 if ( width > -1 )
1844 {
1845 item.m_mask |= wxLIST_MASK_WIDTH;
1846 item.m_width = width;
1847 }
1848 item.m_format = format;
1849
1850 return InsertColumn(col, item);
1851 }
1852
1853 // scroll the control by the given number of pixels (exception: in list view,
1854 // dx is interpreted as number of columns)
1855 bool wxListCtrl::ScrollList(int dx, int dy)
1856 {
1857 if ( !ListView_Scroll(GetHwnd(), dx, dy) )
1858 {
1859 wxLogDebug(wxT("ListView_Scroll(%d, %d) failed"), dx, dy);
1860
1861 return false;
1862 }
1863
1864 return true;
1865 }
1866
1867 // Sort items.
1868
1869 // fn is a function which takes 3 long arguments: item1, item2, data.
1870 // item1 is the long data associated with a first item (NOT the index).
1871 // item2 is the long data associated with a second item (NOT the index).
1872 // data is the same value as passed to SortItems.
1873 // The return value is a negative number if the first item should precede the second
1874 // item, a positive number of the second item should precede the first,
1875 // or zero if the two items are equivalent.
1876
1877 // data is arbitrary data to be passed to the sort function.
1878
1879 // Internal structures for proxying the user compare function
1880 // so that we can pass it the *real* user data
1881
1882 // translate lParam data and call user func
1883 struct wxInternalDataSort
1884 {
1885 wxListCtrlCompare user_fn;
1886 wxIntPtr data;
1887 };
1888
1889 int CALLBACK wxInternalDataCompareFunc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort)
1890 {
1891 wxInternalDataSort * const internalData = (wxInternalDataSort *) lParamSort;
1892
1893 wxMSWListItemData *data1 = (wxMSWListItemData *) lParam1;
1894 wxMSWListItemData *data2 = (wxMSWListItemData *) lParam2;
1895
1896 long d1 = (data1 == NULL ? 0 : data1->lParam);
1897 long d2 = (data2 == NULL ? 0 : data2->lParam);
1898
1899 return internalData->user_fn(d1, d2, internalData->data);
1900
1901 }
1902
1903 bool wxListCtrl::SortItems(wxListCtrlCompare fn, wxIntPtr data)
1904 {
1905 wxInternalDataSort internalData;
1906 internalData.user_fn = fn;
1907 internalData.data = data;
1908
1909 // WPARAM cast is needed for mingw/cygwin
1910 if ( !ListView_SortItems(GetHwnd(),
1911 wxInternalDataCompareFunc,
1912 (WPARAM) &internalData) )
1913 {
1914 wxLogDebug(wxT("ListView_SortItems() failed"));
1915
1916 return false;
1917 }
1918
1919 return true;
1920 }
1921
1922
1923
1924 // ----------------------------------------------------------------------------
1925 // message processing
1926 // ----------------------------------------------------------------------------
1927
1928 bool wxListCtrl::MSWShouldPreProcessMessage(WXMSG* msg)
1929 {
1930 if ( msg->message == WM_KEYDOWN )
1931 {
1932 // Only eat VK_RETURN if not being used by the application in
1933 // conjunction with modifiers
1934 if ( msg->wParam == VK_RETURN && !wxIsAnyModifierDown() )
1935 {
1936 // we need VK_RETURN to generate wxEVT_COMMAND_LIST_ITEM_ACTIVATED
1937 return false;
1938 }
1939 }
1940 return wxControl::MSWShouldPreProcessMessage(msg);
1941 }
1942
1943 bool wxListCtrl::MSWCommand(WXUINT cmd, WXWORD id_)
1944 {
1945 const int id = (signed short)id_;
1946 if (cmd == EN_UPDATE)
1947 {
1948 wxCommandEvent event(wxEVT_COMMAND_TEXT_UPDATED, id);
1949 event.SetEventObject( this );
1950 ProcessCommand(event);
1951 return true;
1952 }
1953 else if (cmd == EN_KILLFOCUS)
1954 {
1955 wxCommandEvent event(wxEVT_KILL_FOCUS, id);
1956 event.SetEventObject( this );
1957 ProcessCommand(event);
1958 return true;
1959 }
1960 else
1961 return false;
1962 }
1963
1964 // utility used by wxListCtrl::MSWOnNotify and by wxDataViewHeaderWindowMSW::MSWOnNotify
1965 int WXDLLIMPEXP_CORE wxMSWGetColumnClicked(NMHDR *nmhdr, POINT *ptClick)
1966 {
1967 // find the column clicked: we have to search for it ourselves as the
1968 // notification message doesn't provide this info
1969
1970 // where did the click occur?
1971 #if defined(__WXWINCE__) && !defined(__HANDHELDPC__) && _WIN32_WCE < 400
1972 if ( nmhdr->code == GN_CONTEXTMENU )
1973 {
1974 *ptClick = ((NMRGINFO*)nmhdr)->ptAction;
1975 }
1976 else
1977 #endif //__WXWINCE__
1978 if ( !::GetCursorPos(ptClick) )
1979 {
1980 wxLogLastError(wxT("GetCursorPos"));
1981 }
1982
1983 // we need to use listctrl coordinates for the event point so this is what
1984 // we return in ptClick, but for comparison with Header_GetItemRect()
1985 // result below we need to use header window coordinates
1986 POINT ptClickHeader = *ptClick;
1987 if ( !::ScreenToClient(nmhdr->hwndFrom, &ptClickHeader) )
1988 {
1989 wxLogLastError(wxT("ScreenToClient(listctrl header)"));
1990 }
1991
1992 if ( !::ScreenToClient(::GetParent(nmhdr->hwndFrom), ptClick) )
1993 {
1994 wxLogLastError(wxT("ScreenToClient(listctrl)"));
1995 }
1996
1997 const int colCount = Header_GetItemCount(nmhdr->hwndFrom);
1998 for ( int col = 0; col < colCount; col++ )
1999 {
2000 RECT rect;
2001 if ( Header_GetItemRect(nmhdr->hwndFrom, col, &rect) )
2002 {
2003 if ( ::PtInRect(&rect, ptClickHeader) )
2004 {
2005 return col;
2006 }
2007 }
2008 }
2009
2010 return wxNOT_FOUND;
2011 }
2012
2013 bool wxListCtrl::MSWOnNotify(int idCtrl, WXLPARAM lParam, WXLPARAM *result)
2014 {
2015
2016 // prepare the event
2017 // -----------------
2018
2019 wxListEvent event(wxEVT_NULL, m_windowId);
2020 event.SetEventObject(this);
2021
2022 wxEventType eventType = wxEVT_NULL;
2023
2024 NMHDR *nmhdr = (NMHDR *)lParam;
2025
2026 // if your compiler is as broken as this, you should really change it: this
2027 // code is needed for normal operation! #ifdef below is only useful for
2028 // automatic rebuilds which are done with a very old compiler version
2029 #ifdef HDN_BEGINTRACKA
2030
2031 // check for messages from the header (in report view)
2032 HWND hwndHdr = ListView_GetHeader(GetHwnd());
2033
2034 // is it a message from the header?
2035 if ( nmhdr->hwndFrom == hwndHdr )
2036 {
2037 HD_NOTIFY *nmHDR = (HD_NOTIFY *)nmhdr;
2038
2039 event.m_itemIndex = -1;
2040
2041 bool ignore = false;
2042 switch ( nmhdr->code )
2043 {
2044 // yet another comctl32.dll bug: under NT/W2K it sends Unicode
2045 // TRACK messages even to ANSI programs: on my system I get
2046 // HDN_BEGINTRACKW and HDN_ENDTRACKA!
2047 //
2048 // work around is to simply catch both versions and hope that it
2049 // works (why should this message exist in ANSI and Unicode is
2050 // beyond me as it doesn't deal with strings at all...)
2051 //
2052 // another problem is that HDN_TRACK is not sent at all by header
2053 // with HDS_FULLDRAG style which is used by default by wxListCtrl
2054 // under recent Windows versions (starting from at least XP) so we
2055 // need to use HDN_ITEMCHANGING instead of it
2056 case HDN_BEGINTRACKA:
2057 case HDN_BEGINTRACKW:
2058 eventType = wxEVT_COMMAND_LIST_COL_BEGIN_DRAG;
2059 // fall through
2060
2061 case HDN_ITEMCHANGING:
2062 if ( eventType == wxEVT_NULL )
2063 {
2064 if ( !nmHDR->pitem || !(nmHDR->pitem->mask & HDI_WIDTH) )
2065 {
2066 // something other than the width is being changed,
2067 // ignore it
2068 ignore = true;
2069 break;
2070 }
2071
2072 // also ignore the events sent when the width didn't really
2073 // change: this is not just an optimization but also gets
2074 // rid of a useless and unexpected DRAGGING event which
2075 // would otherwise be sent after the END_DRAG one as we get
2076 // an HDN_ITEMCHANGING after HDN_ENDTRACK for some reason
2077 if ( nmHDR->pitem->cxy == GetColumnWidth(nmHDR->iItem) )
2078 {
2079 ignore = true;
2080 break;
2081 }
2082
2083 eventType = wxEVT_COMMAND_LIST_COL_DRAGGING;
2084 }
2085 // fall through
2086
2087 case HDN_ENDTRACKA:
2088 case HDN_ENDTRACKW:
2089 if ( eventType == wxEVT_NULL )
2090 eventType = wxEVT_COMMAND_LIST_COL_END_DRAG;
2091
2092 event.m_item.m_width = nmHDR->pitem->cxy;
2093 event.m_col = nmHDR->iItem;
2094 break;
2095
2096 #if defined(__WXWINCE__) && !defined(__HANDHELDPC__) && _WIN32_WCE < 400
2097 case GN_CONTEXTMENU:
2098 #endif //__WXWINCE__
2099 case NM_RCLICK:
2100 {
2101 POINT ptClick;
2102
2103 eventType = wxEVT_COMMAND_LIST_COL_RIGHT_CLICK;
2104 event.m_col = wxMSWGetColumnClicked(nmhdr, &ptClick);
2105 event.m_pointDrag.x = ptClick.x;
2106 event.m_pointDrag.y = ptClick.y;
2107 }
2108 break;
2109
2110 case HDN_GETDISPINFOW:
2111 // letting Windows XP handle this message results in mysterious
2112 // crashes in comctl32.dll seemingly because of bad message
2113 // parameters
2114 //
2115 // I have no idea what is the real cause of the bug (which is,
2116 // just to make things interesting, impossible to reproduce
2117 // reliably) but ignoring all these messages does fix it and
2118 // doesn't seem to have any negative consequences
2119 return true;
2120
2121 default:
2122 ignore = true;
2123 }
2124
2125 if ( ignore )
2126 return wxControl::MSWOnNotify(idCtrl, lParam, result);
2127 }
2128 else
2129 #endif // defined(HDN_BEGINTRACKA)
2130 if ( nmhdr->hwndFrom == GetHwnd() )
2131 {
2132 // almost all messages use NM_LISTVIEW
2133 NM_LISTVIEW *nmLV = (NM_LISTVIEW *)nmhdr;
2134
2135 const int iItem = nmLV->iItem;
2136
2137
2138 // If we have a valid item then check if there is a data value
2139 // associated with it and put it in the event.
2140 if ( iItem >= 0 && iItem < GetItemCount() )
2141 {
2142 wxMSWListItemData *internaldata =
2143 MSWGetItemData(iItem);
2144
2145 if ( internaldata )
2146 event.m_item.m_data = internaldata->lParam;
2147 }
2148
2149 bool processed = true;
2150 switch ( nmhdr->code )
2151 {
2152 case LVN_BEGINRDRAG:
2153 eventType = wxEVT_COMMAND_LIST_BEGIN_RDRAG;
2154 // fall through
2155
2156 case LVN_BEGINDRAG:
2157 if ( eventType == wxEVT_NULL )
2158 {
2159 eventType = wxEVT_COMMAND_LIST_BEGIN_DRAG;
2160 }
2161
2162 event.m_itemIndex = iItem;
2163 event.m_pointDrag.x = nmLV->ptAction.x;
2164 event.m_pointDrag.y = nmLV->ptAction.y;
2165 break;
2166
2167 // NB: we have to handle both *A and *W versions here because some
2168 // versions of comctl32.dll send ANSI messages even to the
2169 // Unicode windows
2170 case LVN_BEGINLABELEDITA:
2171 case LVN_BEGINLABELEDITW:
2172 {
2173 wxLV_ITEM item;
2174 if ( nmhdr->code == LVN_BEGINLABELEDITA )
2175 {
2176 item.Init(((LV_DISPINFOA *)lParam)->item);
2177 }
2178 else // LVN_BEGINLABELEDITW
2179 {
2180 item.Init(((LV_DISPINFOW *)lParam)->item);
2181 }
2182
2183 eventType = wxEVT_COMMAND_LIST_BEGIN_LABEL_EDIT;
2184 wxConvertFromMSWListItem(GetHwnd(), event.m_item, item);
2185 event.m_itemIndex = event.m_item.m_itemId;
2186 }
2187 break;
2188
2189 case LVN_ENDLABELEDITA:
2190 case LVN_ENDLABELEDITW:
2191 {
2192 wxLV_ITEM item;
2193 if ( nmhdr->code == LVN_ENDLABELEDITA )
2194 {
2195 item.Init(((LV_DISPINFOA *)lParam)->item);
2196 }
2197 else // LVN_ENDLABELEDITW
2198 {
2199 item.Init(((LV_DISPINFOW *)lParam)->item);
2200 }
2201
2202 // was editing cancelled?
2203 const LV_ITEM& lvi = (LV_ITEM)item;
2204 if ( !lvi.pszText || lvi.iItem == -1 )
2205 {
2206 // EDIT control will be deleted by the list control
2207 // itself so prevent us from deleting it as well
2208 DeleteEditControl();
2209
2210 event.SetEditCanceled(true);
2211 }
2212
2213 eventType = wxEVT_COMMAND_LIST_END_LABEL_EDIT;
2214 wxConvertFromMSWListItem(NULL, event.m_item, item);
2215 event.m_itemIndex = event.m_item.m_itemId;
2216 }
2217 break;
2218
2219 case LVN_COLUMNCLICK:
2220 eventType = wxEVT_COMMAND_LIST_COL_CLICK;
2221 event.m_itemIndex = -1;
2222 event.m_col = nmLV->iSubItem;
2223 break;
2224
2225 case LVN_DELETEALLITEMS:
2226 eventType = wxEVT_COMMAND_LIST_DELETE_ALL_ITEMS;
2227 event.m_itemIndex = -1;
2228 break;
2229
2230 case LVN_DELETEITEM:
2231 if ( m_count == 0 )
2232 {
2233 // this should be prevented by the post-processing code
2234 // below, but "just in case"
2235 return false;
2236 }
2237
2238 eventType = wxEVT_COMMAND_LIST_DELETE_ITEM;
2239 event.m_itemIndex = iItem;
2240
2241 // delete the associated internal data
2242 if ( wxMSWListItemData *data = MSWGetItemData(iItem) )
2243 {
2244 const unsigned count = m_internalData.size();
2245 for ( unsigned n = 0; n < count; n++ )
2246 {
2247 if ( m_internalData[n] == data )
2248 {
2249 m_internalData.erase(m_internalData.begin() + n);
2250 wxDELETE(data);
2251 break;
2252 }
2253 }
2254
2255 wxASSERT_MSG( !data, "invalid internal data pointer?" );
2256 }
2257 break;
2258
2259 case LVN_INSERTITEM:
2260 eventType = wxEVT_COMMAND_LIST_INSERT_ITEM;
2261 event.m_itemIndex = iItem;
2262 break;
2263
2264 case LVN_ITEMCHANGED:
2265 // we translate this catch all message into more interesting
2266 // (and more easy to process) wxWidgets events
2267
2268 // first of all, we deal with the state change events only and
2269 // only for valid items (item == -1 for the virtual list
2270 // control)
2271 if ( nmLV->uChanged & LVIF_STATE && iItem != -1 )
2272 {
2273 // temp vars for readability
2274 const UINT stOld = nmLV->uOldState;
2275 const UINT stNew = nmLV->uNewState;
2276
2277 event.m_item.SetId(iItem);
2278 event.m_item.SetMask(wxLIST_MASK_TEXT |
2279 wxLIST_MASK_IMAGE |
2280 wxLIST_MASK_DATA);
2281 GetItem(event.m_item);
2282
2283 // has the focus changed?
2284 if ( !(stOld & LVIS_FOCUSED) && (stNew & LVIS_FOCUSED) )
2285 {
2286 eventType = wxEVT_COMMAND_LIST_ITEM_FOCUSED;
2287 event.m_itemIndex = iItem;
2288 }
2289
2290 if ( (stNew & LVIS_SELECTED) != (stOld & LVIS_SELECTED) )
2291 {
2292 if ( eventType != wxEVT_NULL )
2293 {
2294 // focus and selection have both changed: send the
2295 // focus event from here and the selection one
2296 // below
2297 event.SetEventType(eventType);
2298 (void)HandleWindowEvent(event);
2299 }
2300 else // no focus event to send
2301 {
2302 // then need to set m_itemIndex as it wasn't done
2303 // above
2304 event.m_itemIndex = iItem;
2305 }
2306
2307 eventType = stNew & LVIS_SELECTED
2308 ? wxEVT_COMMAND_LIST_ITEM_SELECTED
2309 : wxEVT_COMMAND_LIST_ITEM_DESELECTED;
2310 }
2311 }
2312
2313 if ( eventType == wxEVT_NULL )
2314 {
2315 // not an interesting event for us
2316 return false;
2317 }
2318
2319 break;
2320
2321 case LVN_KEYDOWN:
2322 {
2323 LV_KEYDOWN *info = (LV_KEYDOWN *)lParam;
2324 WORD wVKey = info->wVKey;
2325
2326 // get the current selection
2327 long lItem = GetNextItem(-1,
2328 wxLIST_NEXT_ALL,
2329 wxLIST_STATE_SELECTED);
2330
2331 // <Enter> or <Space> activate the selected item if any (but
2332 // not with any modifiers as they have a predefined meaning
2333 // then)
2334 if ( lItem != -1 &&
2335 (wVKey == VK_RETURN || wVKey == VK_SPACE) &&
2336 !wxIsAnyModifierDown() )
2337 {
2338 eventType = wxEVT_COMMAND_LIST_ITEM_ACTIVATED;
2339 }
2340 else
2341 {
2342 eventType = wxEVT_COMMAND_LIST_KEY_DOWN;
2343
2344 event.m_code = wxMSWKeyboard::VKToWX(wVKey);
2345 }
2346
2347 event.m_itemIndex =
2348 event.m_item.m_itemId = lItem;
2349
2350 if ( lItem != -1 )
2351 {
2352 // fill the other fields too
2353 event.m_item.m_text = GetItemText(lItem);
2354 event.m_item.m_data = GetItemData(lItem);
2355 }
2356 }
2357 break;
2358
2359 case NM_DBLCLK:
2360 // if the user processes it in wxEVT_COMMAND_LEFT_CLICK(), don't do
2361 // anything else
2362 if ( wxControl::MSWOnNotify(idCtrl, lParam, result) )
2363 {
2364 return true;
2365 }
2366
2367 // else translate it into wxEVT_COMMAND_LIST_ITEM_ACTIVATED event
2368 // if it happened on an item (and not on empty place)
2369 if ( iItem == -1 )
2370 {
2371 // not on item
2372 return false;
2373 }
2374
2375 eventType = wxEVT_COMMAND_LIST_ITEM_ACTIVATED;
2376 event.m_itemIndex = iItem;
2377 event.m_item.m_text = GetItemText(iItem);
2378 event.m_item.m_data = GetItemData(iItem);
2379 break;
2380
2381 #if defined(__WXWINCE__) && !defined(__HANDHELDPC__) && _WIN32_WCE < 400
2382 case GN_CONTEXTMENU:
2383 #endif //__WXWINCE__
2384 case NM_RCLICK:
2385 // if the user processes it in wxEVT_COMMAND_RIGHT_CLICK(),
2386 // don't do anything else
2387 if ( wxControl::MSWOnNotify(idCtrl, lParam, result) )
2388 {
2389 return true;
2390 }
2391
2392 // else translate it into wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK event
2393 LV_HITTESTINFO lvhti;
2394 wxZeroMemory(lvhti);
2395
2396 #if defined(__WXWINCE__) && !defined(__HANDHELDPC__) && _WIN32_WCE < 400
2397 if ( nmhdr->code == GN_CONTEXTMENU )
2398 {
2399 lvhti.pt = ((NMRGINFO*)nmhdr)->ptAction;
2400 }
2401 else
2402 #endif //__WXWINCE__
2403 {
2404 ::GetCursorPos(&(lvhti.pt));
2405 }
2406
2407 ::ScreenToClient(GetHwnd(), &lvhti.pt);
2408 if ( ListView_HitTest(GetHwnd(), &lvhti) != -1 )
2409 {
2410 if ( lvhti.flags & LVHT_ONITEM )
2411 {
2412 eventType = wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK;
2413 event.m_itemIndex = lvhti.iItem;
2414 event.m_pointDrag.x = lvhti.pt.x;
2415 event.m_pointDrag.y = lvhti.pt.y;
2416 }
2417 }
2418 break;
2419
2420 #ifdef NM_CUSTOMDRAW
2421 case NM_CUSTOMDRAW:
2422 *result = OnCustomDraw(lParam);
2423
2424 return *result != CDRF_DODEFAULT;
2425 #endif // _WIN32_IE >= 0x300
2426
2427 case LVN_ODCACHEHINT:
2428 {
2429 const NM_CACHEHINT *cacheHint = (NM_CACHEHINT *)lParam;
2430
2431 eventType = wxEVT_COMMAND_LIST_CACHE_HINT;
2432
2433 // we get some really stupid cache hints like ones for
2434 // items in range 0..0 for an empty control or, after
2435 // deleting an item, for items in invalid range -- filter
2436 // this garbage out
2437 if ( cacheHint->iFrom > cacheHint->iTo )
2438 return false;
2439
2440 event.m_oldItemIndex = cacheHint->iFrom;
2441
2442 const long iMax = GetItemCount();
2443 event.m_itemIndex = cacheHint->iTo < iMax ? cacheHint->iTo
2444 : iMax - 1;
2445 }
2446 break;
2447
2448 #ifdef HAVE_NMLVFINDITEM
2449 case LVN_ODFINDITEM:
2450 // this message is only used with the virtual list control but
2451 // even there we don't want to always use it: in a control with
2452 // sufficiently big number of items (defined as > 1000 here),
2453 // accidentally pressing a key could result in hanging an
2454 // application waiting while it performs linear search
2455 if ( IsVirtual() && GetItemCount() <= 1000 )
2456 {
2457 NMLVFINDITEM* pFindInfo = (NMLVFINDITEM*)lParam;
2458
2459 // no match by default
2460 *result = -1;
2461
2462 // we only handle string-based searches here
2463 //
2464 // TODO: what about LVFI_PARTIAL, should we handle this?
2465 if ( !(pFindInfo->lvfi.flags & LVFI_STRING) )
2466 {
2467 return false;
2468 }
2469
2470 const wxChar * const searchstr = pFindInfo->lvfi.psz;
2471 const size_t len = wxStrlen(searchstr);
2472
2473 // this is the first item we should examine, search from it
2474 // wrapping if necessary
2475 const int startPos = pFindInfo->iStart;
2476 const int maxPos = GetItemCount();
2477 wxCHECK_MSG( startPos <= maxPos, false,
2478 wxT("bad starting position in LVN_ODFINDITEM") );
2479
2480 int currentPos = startPos;
2481 do
2482 {
2483 // wrap to the beginning if necessary
2484 if ( currentPos == maxPos )
2485 {
2486 // somewhat surprisingly, LVFI_WRAP isn't set in
2487 // flags but we still should wrap
2488 currentPos = 0;
2489 }
2490
2491 // does this item begin with searchstr?
2492 if ( wxStrnicmp(searchstr,
2493 GetItemText(currentPos), len) == 0 )
2494 {
2495 *result = currentPos;
2496 break;
2497 }
2498 }
2499 while ( ++currentPos != startPos );
2500
2501 if ( *result == -1 )
2502 {
2503 // not found
2504 return false;
2505 }
2506
2507 SetItemState(*result,
2508 wxLIST_STATE_SELECTED | wxLIST_STATE_FOCUSED,
2509 wxLIST_STATE_SELECTED | wxLIST_STATE_FOCUSED);
2510 EnsureVisible(*result);
2511 return true;
2512 }
2513 else
2514 {
2515 processed = false;
2516 }
2517 break;
2518 #endif // HAVE_NMLVFINDITEM
2519
2520 case LVN_GETDISPINFO:
2521 if ( IsVirtual() )
2522 {
2523 LV_DISPINFO *info = (LV_DISPINFO *)lParam;
2524
2525 LV_ITEM& lvi = info->item;
2526 long item = lvi.iItem;
2527
2528 if ( lvi.mask & LVIF_TEXT )
2529 {
2530 wxString text = OnGetItemText(item, lvi.iSubItem);
2531 wxStrlcpy(lvi.pszText, text.c_str(), lvi.cchTextMax);
2532 }
2533
2534 // see comment at the end of wxListCtrl::GetColumn()
2535 #ifdef NM_CUSTOMDRAW
2536 if ( lvi.mask & LVIF_IMAGE )
2537 {
2538 lvi.iImage = OnGetItemColumnImage(item, lvi.iSubItem);
2539 }
2540 #endif // NM_CUSTOMDRAW
2541
2542 // even though we never use LVM_SETCALLBACKMASK, we still
2543 // can get messages with LVIF_STATE in lvi.mask under Vista
2544 if ( lvi.mask & LVIF_STATE )
2545 {
2546 // we don't have anything to return from here...
2547 lvi.stateMask = 0;
2548 }
2549
2550 return true;
2551 }
2552 // fall through
2553
2554 default:
2555 processed = false;
2556 }
2557
2558 if ( !processed )
2559 return wxControl::MSWOnNotify(idCtrl, lParam, result);
2560 }
2561 else
2562 {
2563 // where did this one come from?
2564 return false;
2565 }
2566
2567 // process the event
2568 // -----------------
2569
2570 event.SetEventType(eventType);
2571
2572 // fill in the item before passing it to the event handler if we do have a
2573 // valid item index and haven't filled it yet (e.g. for LVN_ITEMCHANGED)
2574 if ( event.m_itemIndex != -1 && !event.m_item.GetMask() )
2575 {
2576 wxListItem& item = event.m_item;
2577
2578 item.SetId(event.m_itemIndex);
2579 item.SetMask(wxLIST_MASK_TEXT | wxLIST_MASK_IMAGE | wxLIST_MASK_DATA);
2580 GetItem(item);
2581 }
2582
2583 bool processed = HandleWindowEvent(event);
2584
2585 // post processing
2586 // ---------------
2587 switch ( nmhdr->code )
2588 {
2589 case LVN_DELETEALLITEMS:
2590 // always return true to suppress all additional LVN_DELETEITEM
2591 // notifications - this makes deleting all items from a list ctrl
2592 // much faster
2593 *result = TRUE;
2594
2595 // also, we may free all user data now (couldn't do it before as
2596 // the user should have access to it in OnDeleteAllItems() handler)
2597 FreeAllInternalData();
2598
2599 // the control is empty now, synchronize the cached number of items
2600 // with the real one
2601 m_count = 0;
2602 return true;
2603
2604 case LVN_ENDLABELEDITA:
2605 case LVN_ENDLABELEDITW:
2606 // logic here is inverted compared to all the other messages
2607 *result = event.IsAllowed();
2608
2609 // EDIT control will be deleted by the list control itself so
2610 // prevent us from deleting it as well
2611 DeleteEditControl();
2612
2613 return true;
2614 }
2615
2616 if ( processed )
2617 *result = !event.IsAllowed();
2618
2619 return processed;
2620 }
2621
2622 // ----------------------------------------------------------------------------
2623 // custom draw stuff
2624 // ----------------------------------------------------------------------------
2625
2626 // see comment at the end of wxListCtrl::GetColumn()
2627 #ifdef NM_CUSTOMDRAW // _WIN32_IE >= 0x0300
2628
2629 static RECT GetCustomDrawnItemRect(const NMCUSTOMDRAW& nmcd)
2630 {
2631 RECT rc;
2632 wxGetListCtrlItemRect(nmcd.hdr.hwndFrom, nmcd.dwItemSpec, LVIR_BOUNDS, rc);
2633
2634 RECT rcIcon;
2635 wxGetListCtrlItemRect(nmcd.hdr.hwndFrom, nmcd.dwItemSpec, LVIR_ICON, rcIcon);
2636
2637 // exclude the icon part, neither the selection background nor focus rect
2638 // should cover it
2639 rc.left = rcIcon.right;
2640
2641 return rc;
2642 }
2643
2644 static
2645 bool HandleSubItemPrepaint(LPNMLVCUSTOMDRAW pLVCD, HFONT hfont, int colCount)
2646 {
2647 NMCUSTOMDRAW& nmcd = pLVCD->nmcd;
2648
2649 HDC hdc = nmcd.hdc;
2650 HWND hwndList = nmcd.hdr.hwndFrom;
2651 const int col = pLVCD->iSubItem;
2652 const DWORD item = nmcd.dwItemSpec;
2653
2654 // the font must be valid, otherwise we wouldn't be painting the item at all
2655 SelectInHDC selFont(hdc, hfont);
2656
2657 // get the rectangle to paint
2658 int subitem = colCount ? col + 1 : col;
2659 RECT rc;
2660 wxGetListCtrlSubItemRect(hwndList, item, subitem, LVIR_BOUNDS, rc);
2661 rc.left += 6;
2662
2663 // get the image and text to draw
2664 wxChar text[512];
2665 LV_ITEM it;
2666 wxZeroMemory(it);
2667 it.mask = LVIF_TEXT | LVIF_IMAGE;
2668 it.iItem = item;
2669 it.iSubItem = col;
2670 it.pszText = text;
2671 it.cchTextMax = WXSIZEOF(text);
2672 ListView_GetItem(hwndList, &it);
2673
2674 HIMAGELIST himl = ListView_GetImageList(hwndList, LVSIL_SMALL);
2675 if ( himl && ImageList_GetImageCount(himl) )
2676 {
2677 if ( it.iImage != -1 )
2678 {
2679 ImageList_Draw(himl, it.iImage, hdc, rc.left, rc.top,
2680 nmcd.uItemState & CDIS_SELECTED ? ILD_SELECTED
2681 : ILD_TRANSPARENT);
2682 }
2683
2684 // notice that even if this item doesn't have any image, the list
2685 // control still leaves space for the image in the first column if the
2686 // image list is not empty (presumably so that items with and without
2687 // images align?)
2688 if ( it.iImage != -1 || it.iSubItem == 0 )
2689 {
2690 int wImage, hImage;
2691 ImageList_GetIconSize(himl, &wImage, &hImage);
2692
2693 rc.left += wImage + 2;
2694 }
2695 }
2696
2697 ::SetBkMode(hdc, TRANSPARENT);
2698
2699 UINT fmt = DT_SINGLELINE |
2700 #ifndef __WXWINCE__
2701 DT_WORD_ELLIPSIS |
2702 #endif // __WXWINCE__
2703 DT_NOPREFIX |
2704 DT_VCENTER;
2705
2706 LV_COLUMN lvCol;
2707 wxZeroMemory(lvCol);
2708 lvCol.mask = LVCF_FMT;
2709 if ( ListView_GetColumn(hwndList, col, &lvCol) )
2710 {
2711 switch ( lvCol.fmt & LVCFMT_JUSTIFYMASK )
2712 {
2713 case LVCFMT_LEFT:
2714 fmt |= DT_LEFT;
2715 break;
2716
2717 case LVCFMT_CENTER:
2718 fmt |= DT_CENTER;
2719 break;
2720
2721 case LVCFMT_RIGHT:
2722 fmt |= DT_RIGHT;
2723 break;
2724 }
2725 }
2726 //else: failed to get alignment, assume it's DT_LEFT (default)
2727
2728 DrawText(hdc, text, -1, &rc, fmt);
2729
2730 return true;
2731 }
2732
2733 static void HandleItemPostpaint(NMCUSTOMDRAW nmcd)
2734 {
2735 if ( nmcd.uItemState & CDIS_FOCUS )
2736 {
2737 RECT rc = GetCustomDrawnItemRect(nmcd);
2738
2739 // don't use the provided HDC, it's in some strange state by now
2740 ::DrawFocusRect(WindowHDC(nmcd.hdr.hwndFrom), &rc);
2741 }
2742 }
2743
2744 // pLVCD->clrText and clrTextBk should contain the colours to use
2745 static void HandleItemPaint(LPNMLVCUSTOMDRAW pLVCD, HFONT hfont)
2746 {
2747 NMCUSTOMDRAW& nmcd = pLVCD->nmcd; // just a shortcut
2748
2749 const HWND hwndList = nmcd.hdr.hwndFrom;
2750 const int item = nmcd.dwItemSpec;
2751
2752 // unfortunately we can't trust CDIS_SELECTED, it is often set even when
2753 // the item is not at all selected for some reason (comctl32 6), but we
2754 // also can't always trust ListView_GetItem() as it could return the old
2755 // item status if we're called just after the (de)selection, so remember
2756 // the last item to gain selection and also check for it here
2757 for ( int i = -1;; )
2758 {
2759 i = ListView_GetNextItem(hwndList, i, LVNI_SELECTED);
2760 if ( i == -1 )
2761 {
2762 nmcd.uItemState &= ~CDIS_SELECTED;
2763 break;
2764 }
2765
2766 if ( i == item )
2767 {
2768 nmcd.uItemState |= CDIS_SELECTED;
2769 break;
2770 }
2771 }
2772
2773 // same thing for CDIS_FOCUS (except simpler as there is only one of them)
2774 //
2775 // NB: cast is needed to work around the bug in mingw32 headers which don't
2776 // have it inside ListView_GetNextItem() itself (unlike SDK ones)
2777 if ( ::GetFocus() == hwndList &&
2778 ListView_GetNextItem(
2779 hwndList, static_cast<WPARAM>(-1), LVNI_FOCUSED) == item )
2780 {
2781 nmcd.uItemState |= CDIS_FOCUS;
2782 }
2783 else
2784 {
2785 nmcd.uItemState &= ~CDIS_FOCUS;
2786 }
2787
2788 if ( nmcd.uItemState & CDIS_SELECTED )
2789 {
2790 int syscolFg, syscolBg;
2791 if ( ::GetFocus() == hwndList )
2792 {
2793 syscolFg = COLOR_HIGHLIGHTTEXT;
2794 syscolBg = COLOR_HIGHLIGHT;
2795 }
2796 else // selected but unfocused
2797 {
2798 syscolFg = COLOR_WINDOWTEXT;
2799 syscolBg = COLOR_BTNFACE;
2800
2801 // don't grey out the icon in this case neither
2802 nmcd.uItemState &= ~CDIS_SELECTED;
2803 }
2804
2805 pLVCD->clrText = ::GetSysColor(syscolFg);
2806 pLVCD->clrTextBk = ::GetSysColor(syscolBg);
2807 }
2808 //else: not selected, use normal colours from pLVCD
2809
2810 HDC hdc = nmcd.hdc;
2811 RECT rc = GetCustomDrawnItemRect(nmcd);
2812
2813 ::SetTextColor(hdc, pLVCD->clrText);
2814 ::FillRect(hdc, &rc, AutoHBRUSH(pLVCD->clrTextBk));
2815
2816 // we could use CDRF_NOTIFYSUBITEMDRAW here but it results in weird repaint
2817 // problems so just draw everything except the focus rect from here instead
2818 const int colCount = Header_GetItemCount(ListView_GetHeader(hwndList));
2819 for ( int col = 0; col < colCount; col++ )
2820 {
2821 pLVCD->iSubItem = col;
2822 HandleSubItemPrepaint(pLVCD, hfont, colCount);
2823 }
2824
2825 HandleItemPostpaint(nmcd);
2826 }
2827
2828 static WXLPARAM HandleItemPrepaint(wxListCtrl *listctrl,
2829 LPNMLVCUSTOMDRAW pLVCD,
2830 wxListItemAttr *attr)
2831 {
2832 if ( !attr )
2833 {
2834 // nothing to do for this item
2835 return CDRF_DODEFAULT;
2836 }
2837
2838
2839 // set the colours to use for text drawing
2840 pLVCD->clrText = attr->HasTextColour()
2841 ? wxColourToRGB(attr->GetTextColour())
2842 : wxColourToRGB(listctrl->GetTextColour());
2843 pLVCD->clrTextBk = attr->HasBackgroundColour()
2844 ? wxColourToRGB(attr->GetBackgroundColour())
2845 : wxColourToRGB(listctrl->GetBackgroundColour());
2846
2847 // select the font if non default one is specified
2848 if ( attr->HasFont() )
2849 {
2850 wxFont font = attr->GetFont();
2851 if ( font.GetEncoding() != wxFONTENCODING_SYSTEM )
2852 {
2853 // the standard control ignores the font encoding/charset, at least
2854 // with recent comctl32.dll versions (5 and 6, it uses to work with
2855 // 4.something) so we have to draw the item entirely ourselves in
2856 // this case
2857 HandleItemPaint(pLVCD, GetHfontOf(font));
2858 return CDRF_SKIPDEFAULT;
2859 }
2860
2861 ::SelectObject(pLVCD->nmcd.hdc, GetHfontOf(font));
2862
2863 return CDRF_NEWFONT;
2864 }
2865
2866 return CDRF_DODEFAULT;
2867 }
2868
2869 WXLPARAM wxListCtrl::OnCustomDraw(WXLPARAM lParam)
2870 {
2871 LPNMLVCUSTOMDRAW pLVCD = (LPNMLVCUSTOMDRAW)lParam;
2872 NMCUSTOMDRAW& nmcd = pLVCD->nmcd;
2873 switch ( nmcd.dwDrawStage )
2874 {
2875 case CDDS_PREPAINT:
2876 // if we've got any items with non standard attributes,
2877 // notify us before painting each item
2878 //
2879 // for virtual controls, always suppose that we have attributes as
2880 // there is no way to check for this
2881 if ( IsVirtual() || m_hasAnyAttr )
2882 return CDRF_NOTIFYITEMDRAW;
2883 break;
2884
2885 case CDDS_ITEMPREPAINT:
2886 // get a message for each subitem
2887 return CDRF_NOTIFYITEMDRAW;
2888
2889 case CDDS_SUBITEM | CDDS_ITEMPREPAINT:
2890 const int item = nmcd.dwItemSpec;
2891 const int column = pLVCD->iSubItem;
2892
2893 // we get this message with item == 0 for an empty control, we
2894 // must ignore it as calling OnGetItemAttr() would be wrong
2895 if ( item < 0 || item >= GetItemCount() )
2896 break;
2897 // same for columns
2898 if ( column < 0 || column >= GetColumnCount() )
2899 break;
2900
2901 return HandleItemPrepaint(this, pLVCD, DoGetItemColumnAttr(item, column));
2902 }
2903
2904 return CDRF_DODEFAULT;
2905 }
2906
2907 #endif // NM_CUSTOMDRAW supported
2908
2909 // Necessary for drawing hrules and vrules, if specified
2910 void wxListCtrl::OnPaint(wxPaintEvent& event)
2911 {
2912 const int itemCount = GetItemCount();
2913 const bool drawHRules = HasFlag(wxLC_HRULES);
2914 const bool drawVRules = HasFlag(wxLC_VRULES);
2915
2916 if (!InReportView() || !(drawHRules || drawVRules) || !itemCount)
2917 {
2918 event.Skip();
2919 return;
2920 }
2921
2922 wxPaintDC dc(this);
2923
2924 wxControl::OnPaint(event);
2925
2926 // Reset the device origin since it may have been set
2927 dc.SetDeviceOrigin(0, 0);
2928
2929 wxPen pen(wxSystemSettings::GetColour(wxSYS_COLOUR_3DLIGHT));
2930 dc.SetPen(pen);
2931 dc.SetBrush(* wxTRANSPARENT_BRUSH);
2932
2933 wxSize clientSize = GetClientSize();
2934 wxRect itemRect;
2935
2936 if (drawHRules)
2937 {
2938 const long top = GetTopItem();
2939 for ( int i = top; i < top + GetCountPerPage() + 1; i++ )
2940 {
2941 if (GetItemRect(i, itemRect))
2942 {
2943 int cy = itemRect.GetTop();
2944 if (i != 0) // Don't draw the first one
2945 {
2946 dc.DrawLine(0, cy, clientSize.x, cy);
2947 }
2948 // Draw last line
2949 if (i == itemCount - 1)
2950 {
2951 cy = itemRect.GetBottom();
2952 dc.DrawLine(0, cy, clientSize.x, cy);
2953 break;
2954 }
2955 }
2956 }
2957 }
2958
2959 if (drawVRules)
2960 {
2961 wxRect firstItemRect;
2962 GetItemRect(0, firstItemRect);
2963
2964 if (GetItemRect(itemCount - 1, itemRect))
2965 {
2966 // this is a fix for bug 673394: erase the pixels which we would
2967 // otherwise leave on the screen
2968 static const int gap = 2;
2969 dc.SetPen(*wxTRANSPARENT_PEN);
2970 dc.SetBrush(wxBrush(GetBackgroundColour()));
2971 dc.DrawRectangle(0, firstItemRect.GetY() - gap,
2972 clientSize.GetWidth(), gap);
2973
2974 dc.SetPen(pen);
2975 dc.SetBrush(*wxTRANSPARENT_BRUSH);
2976
2977 const int numCols = GetColumnCount();
2978 wxVector<int> indexArray(numCols);
2979 if ( !ListView_GetColumnOrderArray(GetHwnd(),
2980 numCols,
2981 &indexArray[0]) )
2982 {
2983 wxFAIL_MSG( wxT("invalid column index array in OnPaint()") );
2984 return;
2985 }
2986
2987 int x = itemRect.GetX();
2988 for (int col = 0; col < numCols; col++)
2989 {
2990 int colWidth = GetColumnWidth(indexArray[col]);
2991 x += colWidth ;
2992 dc.DrawLine(x-1, firstItemRect.GetY() - gap,
2993 x-1, itemRect.GetBottom());
2994 }
2995 }
2996 }
2997 }
2998
2999 WXLRESULT
3000 wxListCtrl::MSWWindowProc(WXUINT nMsg, WXWPARAM wParam, WXLPARAM lParam)
3001 {
3002 switch ( nMsg )
3003 {
3004 #ifdef WM_PRINT
3005 case WM_PRINT:
3006 // we should bypass our own WM_PRINT handling as we don't handle
3007 // PRF_CHILDREN flag, so leave it to the native control itself
3008 return MSWDefWindowProc(nMsg, wParam, lParam);
3009 #endif // WM_PRINT
3010
3011 case WM_CONTEXTMENU:
3012 // because this message is propagated upwards the child-parent
3013 // chain, we get it for the right clicks on the header window but
3014 // this is confusing in wx as right clicking there already
3015 // generates a separate wxEVT_COMMAND_LIST_COL_RIGHT_CLICK event
3016 // so just ignore them
3017 if ( (HWND)wParam == ListView_GetHeader(GetHwnd()) )
3018 return 0;
3019 //else: break
3020 }
3021
3022 return wxControl::MSWWindowProc(nMsg, wParam, lParam);
3023 }
3024
3025 // ----------------------------------------------------------------------------
3026 // virtual list controls
3027 // ----------------------------------------------------------------------------
3028
3029 wxString wxListCtrl::OnGetItemText(long WXUNUSED(item), long WXUNUSED(col)) const
3030 {
3031 // this is a pure virtual function, in fact - which is not really pure
3032 // because the controls which are not virtual don't need to implement it
3033 wxFAIL_MSG( wxT("wxListCtrl::OnGetItemText not supposed to be called") );
3034
3035 return wxEmptyString;
3036 }
3037
3038 int wxListCtrl::OnGetItemImage(long WXUNUSED(item)) const
3039 {
3040 wxCHECK_MSG(!GetImageList(wxIMAGE_LIST_SMALL),
3041 -1,
3042 wxT("List control has an image list, OnGetItemImage or OnGetItemColumnImage should be overridden."));
3043 return -1;
3044 }
3045
3046 int wxListCtrl::OnGetItemColumnImage(long item, long column) const
3047 {
3048 if (!column)
3049 return OnGetItemImage(item);
3050
3051 return -1;
3052 }
3053
3054 wxListItemAttr *wxListCtrl::OnGetItemAttr(long WXUNUSED_UNLESS_DEBUG(item)) const
3055 {
3056 wxASSERT_MSG( item >= 0 && item < GetItemCount(),
3057 wxT("invalid item index in OnGetItemAttr()") );
3058
3059 // no attributes by default
3060 return NULL;
3061 }
3062
3063 wxListItemAttr *wxListCtrl::DoGetItemColumnAttr(long item, long column) const
3064 {
3065 if ( IsVirtual() )
3066 return OnGetItemColumnAttr(item, column);
3067
3068 wxMSWListItemData * const data = MSWGetItemData(item);
3069 return data ? data->attr : NULL;
3070 }
3071
3072 void wxListCtrl::SetItemCount(long count)
3073 {
3074 wxASSERT_MSG( IsVirtual(), wxT("this is for virtual controls only") );
3075
3076 if ( !::SendMessage(GetHwnd(), LVM_SETITEMCOUNT, (WPARAM)count,
3077 LVSICF_NOSCROLL | LVSICF_NOINVALIDATEALL) )
3078 {
3079 wxLogLastError(wxT("ListView_SetItemCount"));
3080 }
3081 m_count = count;
3082 wxASSERT_MSG( m_count == ListView_GetItemCount(GetHwnd()),
3083 wxT("m_count should match ListView_GetItemCount"));
3084 }
3085
3086 void wxListCtrl::RefreshItem(long item)
3087 {
3088 RefreshItems(item, item);
3089 }
3090
3091 void wxListCtrl::RefreshItems(long itemFrom, long itemTo)
3092 {
3093 ListView_RedrawItems(GetHwnd(), itemFrom, itemTo);
3094 }
3095
3096 // ----------------------------------------------------------------------------
3097 // wxWin <-> MSW items conversions
3098 // ----------------------------------------------------------------------------
3099
3100 static void wxConvertFromMSWListItem(HWND hwndListCtrl,
3101 wxListItem& info,
3102 LV_ITEM& lvItem)
3103 {
3104 wxMSWListItemData *internaldata =
3105 (wxMSWListItemData *) lvItem.lParam;
3106
3107 if (internaldata)
3108 info.m_data = internaldata->lParam;
3109
3110 info.m_mask = 0;
3111 info.m_state = 0;
3112 info.m_stateMask = 0;
3113 info.m_itemId = lvItem.iItem;
3114
3115 long oldMask = lvItem.mask;
3116
3117 bool needText = false;
3118 if (hwndListCtrl != 0)
3119 {
3120 if ( lvItem.mask & LVIF_TEXT )
3121 needText = false;
3122 else
3123 needText = true;
3124
3125 if ( needText )
3126 {
3127 lvItem.pszText = new wxChar[513];
3128 lvItem.cchTextMax = 512;
3129 }
3130 lvItem.mask |= LVIF_TEXT | LVIF_IMAGE | LVIF_PARAM;
3131 ::SendMessage(hwndListCtrl, LVM_GETITEM, 0, (LPARAM)& lvItem);
3132 }
3133
3134 if ( lvItem.mask & LVIF_STATE )
3135 {
3136 info.m_mask |= wxLIST_MASK_STATE;
3137
3138 if ( lvItem.stateMask & LVIS_CUT)
3139 {
3140 info.m_stateMask |= wxLIST_STATE_CUT;
3141 if ( lvItem.state & LVIS_CUT )
3142 info.m_state |= wxLIST_STATE_CUT;
3143 }
3144 if ( lvItem.stateMask & LVIS_DROPHILITED)
3145 {
3146 info.m_stateMask |= wxLIST_STATE_DROPHILITED;
3147 if ( lvItem.state & LVIS_DROPHILITED )
3148 info.m_state |= wxLIST_STATE_DROPHILITED;
3149 }
3150 if ( lvItem.stateMask & LVIS_FOCUSED)
3151 {
3152 info.m_stateMask |= wxLIST_STATE_FOCUSED;
3153 if ( lvItem.state & LVIS_FOCUSED )
3154 info.m_state |= wxLIST_STATE_FOCUSED;
3155 }
3156 if ( lvItem.stateMask & LVIS_SELECTED)
3157 {
3158 info.m_stateMask |= wxLIST_STATE_SELECTED;
3159 if ( lvItem.state & LVIS_SELECTED )
3160 info.m_state |= wxLIST_STATE_SELECTED;
3161 }
3162 }
3163
3164 if ( lvItem.mask & LVIF_TEXT )
3165 {
3166 info.m_mask |= wxLIST_MASK_TEXT;
3167 info.m_text = lvItem.pszText;
3168 }
3169 if ( lvItem.mask & LVIF_IMAGE )
3170 {
3171 info.m_mask |= wxLIST_MASK_IMAGE;
3172 info.m_image = lvItem.iImage;
3173 }
3174 if ( lvItem.mask & LVIF_PARAM )
3175 info.m_mask |= wxLIST_MASK_DATA;
3176 if ( lvItem.mask & LVIF_DI_SETITEM )
3177 info.m_mask |= wxLIST_SET_ITEM;
3178 info.m_col = lvItem.iSubItem;
3179
3180 if (needText)
3181 {
3182 if (lvItem.pszText)
3183 delete[] lvItem.pszText;
3184 }
3185 lvItem.mask = oldMask;
3186 }
3187
3188 static void wxConvertToMSWFlags(long state, long stateMask, LV_ITEM& lvItem)
3189 {
3190 if (stateMask & wxLIST_STATE_CUT)
3191 {
3192 lvItem.stateMask |= LVIS_CUT;
3193 if (state & wxLIST_STATE_CUT)
3194 lvItem.state |= LVIS_CUT;
3195 }
3196 if (stateMask & wxLIST_STATE_DROPHILITED)
3197 {
3198 lvItem.stateMask |= LVIS_DROPHILITED;
3199 if (state & wxLIST_STATE_DROPHILITED)
3200 lvItem.state |= LVIS_DROPHILITED;
3201 }
3202 if (stateMask & wxLIST_STATE_FOCUSED)
3203 {
3204 lvItem.stateMask |= LVIS_FOCUSED;
3205 if (state & wxLIST_STATE_FOCUSED)
3206 lvItem.state |= LVIS_FOCUSED;
3207 }
3208 if (stateMask & wxLIST_STATE_SELECTED)
3209 {
3210 lvItem.stateMask |= LVIS_SELECTED;
3211 if (state & wxLIST_STATE_SELECTED)
3212 lvItem.state |= LVIS_SELECTED;
3213 }
3214 }
3215
3216 static void wxConvertToMSWListItem(const wxListCtrl *ctrl,
3217 const wxListItem& info,
3218 LV_ITEM& lvItem)
3219 {
3220 if ( ctrl->InReportView() )
3221 {
3222 wxASSERT_MSG( 0 <= info.m_col && info.m_col < ctrl->GetColumnCount(),
3223 "wxListCtrl column index out of bounds" );
3224 }
3225 else // not in report view
3226 {
3227 wxASSERT_MSG( info.m_col == 0, "columns only exist in report view" );
3228 }
3229
3230 lvItem.iItem = (int) info.m_itemId;
3231
3232 lvItem.iImage = info.m_image;
3233 lvItem.stateMask = 0;
3234 lvItem.state = 0;
3235 lvItem.mask = 0;
3236 lvItem.iSubItem = info.m_col;
3237
3238 if (info.m_mask & wxLIST_MASK_STATE)
3239 {
3240 lvItem.mask |= LVIF_STATE;
3241
3242 wxConvertToMSWFlags(info.m_state, info.m_stateMask, lvItem);
3243 }
3244
3245 if (info.m_mask & wxLIST_MASK_TEXT)
3246 {
3247 lvItem.mask |= LVIF_TEXT;
3248 if ( ctrl->HasFlag(wxLC_USER_TEXT) )
3249 {
3250 lvItem.pszText = LPSTR_TEXTCALLBACK;
3251 }
3252 else
3253 {
3254 // pszText is not const, hence the cast
3255 lvItem.pszText = (wxChar *)info.m_text.wx_str();
3256 if ( lvItem.pszText )
3257 lvItem.cchTextMax = info.m_text.length();
3258 else
3259 lvItem.cchTextMax = 0;
3260 }
3261 }
3262 if (info.m_mask & wxLIST_MASK_IMAGE)
3263 lvItem.mask |= LVIF_IMAGE;
3264 }
3265
3266 static void wxConvertToMSWListCol(HWND hwndList,
3267 int col,
3268 const wxListItem& item,
3269 LV_COLUMN& lvCol)
3270 {
3271 wxZeroMemory(lvCol);
3272
3273 if ( item.m_mask & wxLIST_MASK_TEXT )
3274 {
3275 lvCol.mask |= LVCF_TEXT;
3276 lvCol.pszText = (wxChar *)item.m_text.wx_str(); // cast is safe
3277 }
3278
3279 if ( item.m_mask & wxLIST_MASK_FORMAT )
3280 {
3281 lvCol.mask |= LVCF_FMT;
3282
3283 if ( item.m_format == wxLIST_FORMAT_LEFT )
3284 lvCol.fmt = LVCFMT_LEFT;
3285 else if ( item.m_format == wxLIST_FORMAT_RIGHT )
3286 lvCol.fmt = LVCFMT_RIGHT;
3287 else if ( item.m_format == wxLIST_FORMAT_CENTRE )
3288 lvCol.fmt = LVCFMT_CENTER;
3289 }
3290
3291 if ( item.m_mask & wxLIST_MASK_WIDTH )
3292 {
3293 lvCol.mask |= LVCF_WIDTH;
3294 if ( item.m_width == wxLIST_AUTOSIZE)
3295 lvCol.cx = LVSCW_AUTOSIZE;
3296 else if ( item.m_width == wxLIST_AUTOSIZE_USEHEADER)
3297 lvCol.cx = LVSCW_AUTOSIZE_USEHEADER;
3298 else
3299 lvCol.cx = item.m_width;
3300 }
3301
3302 // see comment at the end of wxListCtrl::GetColumn()
3303 #ifdef NM_CUSTOMDRAW // _WIN32_IE >= 0x0300
3304 if ( item.m_mask & wxLIST_MASK_IMAGE )
3305 {
3306 if ( wxApp::GetComCtl32Version() >= 470 )
3307 {
3308 lvCol.mask |= LVCF_IMAGE;
3309
3310 // we use LVCFMT_BITMAP_ON_RIGHT because the images on the right
3311 // seem to be generally nicer than on the left and the generic
3312 // version only draws them on the right (we don't have a flag to
3313 // specify the image location anyhow)
3314 //
3315 // we don't use LVCFMT_COL_HAS_IMAGES because it doesn't seem to
3316 // make any difference in my tests -- but maybe we should?
3317 if ( item.m_image != -1 )
3318 {
3319 // as we're going to overwrite the format field, get its
3320 // current value first -- unless we want to overwrite it anyhow
3321 if ( !(lvCol.mask & LVCF_FMT) )
3322 {
3323 LV_COLUMN lvColOld;
3324 wxZeroMemory(lvColOld);
3325 lvColOld.mask = LVCF_FMT;
3326 if ( ListView_GetColumn(hwndList, col, &lvColOld) )
3327 {
3328 lvCol.fmt = lvColOld.fmt;
3329 }
3330
3331 lvCol.mask |= LVCF_FMT;
3332 }
3333
3334 lvCol.fmt |= LVCFMT_BITMAP_ON_RIGHT | LVCFMT_IMAGE;
3335 }
3336
3337 lvCol.iImage = item.m_image;
3338 }
3339 //else: it doesn't support item images anyhow
3340 }
3341 #endif // _WIN32_IE >= 0x0300
3342 }
3343
3344 #endif // wxUSE_LISTCTRL