1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/listbox.cpp
4 // Author: Julian Smart
5 // Modified by: Vadim Zeitlin (owner drawn stuff)
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 ///////////////////////////////////////////////////////////////////////////////
12 // For compilers that support precompilation, includes "wx.h".
13 #include "wx/wxprec.h"
21 #include "wx/listbox.h"
24 #include "wx/dynarray.h"
25 #include "wx/settings.h"
31 #include "wx/window.h"
34 #include "wx/msw/private.h"
39 #include "wx/ownerdrw.h"
42 #if wxUSE_EXTENDED_RTTI
43 WX_DEFINE_FLAGS( wxListBoxStyle
)
45 wxBEGIN_FLAGS( wxListBoxStyle
)
46 // new style border flags, we put them first to
47 // use them for streaming out
48 wxFLAGS_MEMBER(wxBORDER_SIMPLE
)
49 wxFLAGS_MEMBER(wxBORDER_SUNKEN
)
50 wxFLAGS_MEMBER(wxBORDER_DOUBLE
)
51 wxFLAGS_MEMBER(wxBORDER_RAISED
)
52 wxFLAGS_MEMBER(wxBORDER_STATIC
)
53 wxFLAGS_MEMBER(wxBORDER_NONE
)
55 // old style border flags
56 wxFLAGS_MEMBER(wxSIMPLE_BORDER
)
57 wxFLAGS_MEMBER(wxSUNKEN_BORDER
)
58 wxFLAGS_MEMBER(wxDOUBLE_BORDER
)
59 wxFLAGS_MEMBER(wxRAISED_BORDER
)
60 wxFLAGS_MEMBER(wxSTATIC_BORDER
)
61 wxFLAGS_MEMBER(wxBORDER
)
63 // standard window styles
64 wxFLAGS_MEMBER(wxTAB_TRAVERSAL
)
65 wxFLAGS_MEMBER(wxCLIP_CHILDREN
)
66 wxFLAGS_MEMBER(wxTRANSPARENT_WINDOW
)
67 wxFLAGS_MEMBER(wxWANTS_CHARS
)
68 wxFLAGS_MEMBER(wxFULL_REPAINT_ON_RESIZE
)
69 wxFLAGS_MEMBER(wxALWAYS_SHOW_SB
)
70 wxFLAGS_MEMBER(wxVSCROLL
)
71 wxFLAGS_MEMBER(wxHSCROLL
)
73 wxFLAGS_MEMBER(wxLB_SINGLE
)
74 wxFLAGS_MEMBER(wxLB_MULTIPLE
)
75 wxFLAGS_MEMBER(wxLB_EXTENDED
)
76 wxFLAGS_MEMBER(wxLB_HSCROLL
)
77 wxFLAGS_MEMBER(wxLB_ALWAYS_SB
)
78 wxFLAGS_MEMBER(wxLB_NEEDED_SB
)
79 wxFLAGS_MEMBER(wxLB_SORT
)
81 wxEND_FLAGS( wxListBoxStyle
)
83 IMPLEMENT_DYNAMIC_CLASS_XTI(wxListBox
, wxControlWithItems
,"wx/listbox.h")
85 wxBEGIN_PROPERTIES_TABLE(wxListBox
)
86 wxEVENT_PROPERTY( Select
, wxEVT_COMMAND_LISTBOX_SELECTED
, wxCommandEvent
)
87 wxEVENT_PROPERTY( DoubleClick
, wxEVT_COMMAND_LISTBOX_DOUBLECLICKED
, wxCommandEvent
)
89 wxPROPERTY( Font
, wxFont
, SetFont
, GetFont
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group"))
90 wxPROPERTY_COLLECTION( Choices
, wxArrayString
, wxString
, AppendString
, GetStrings
, 0 /*flags*/ , wxT("Helpstring") , wxT("group") )
91 wxPROPERTY( Selection
,int, SetSelection
, GetSelection
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group") )
92 wxPROPERTY_FLAGS( WindowStyle
, wxListBoxStyle
, long , SetWindowStyleFlag
, GetWindowStyleFlag
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group")) // style
93 wxEND_PROPERTIES_TABLE()
95 wxBEGIN_HANDLERS_TABLE(wxListBox
)
96 wxEND_HANDLERS_TABLE()
98 wxCONSTRUCTOR_4( wxListBox
, wxWindow
* , Parent
, wxWindowID
, Id
, wxPoint
, Position
, wxSize
, Size
)
100 IMPLEMENT_DYNAMIC_CLASS(wxListBox
, wxControlWithItems
)
110 // ============================================================================
111 // list box item declaration and implementation
112 // ============================================================================
114 #if wxUSE_OWNER_DRAWN
116 class wxListBoxItem
: public wxOwnerDrawn
119 wxListBoxItem(const wxString
& str
= wxEmptyString
);
122 wxListBoxItem::wxListBoxItem(const wxString
& str
) : wxOwnerDrawn(str
, false)
124 // no bitmaps/checkmarks
128 wxOwnerDrawn
*wxListBox::CreateLboxItem(size_t WXUNUSED(n
))
130 return new wxListBoxItem();
133 #endif //USE_OWNER_DRAWN
135 // ============================================================================
136 // list box control implementation
137 // ============================================================================
139 // ----------------------------------------------------------------------------
141 // ----------------------------------------------------------------------------
144 wxListBox::wxListBox()
150 bool wxListBox::Create(wxWindow
*parent
,
154 int n
, const wxString choices
[],
156 const wxValidator
& validator
,
157 const wxString
& name
)
162 // initialize base class fields
163 if ( !CreateControl(parent
, id
, pos
, size
, style
, validator
, name
) )
166 // create the native control
167 if ( !MSWCreateControl(_T("LISTBOX"), wxEmptyString
, pos
, size
) )
169 // control creation failed
173 // initialize the contents
174 for ( int i
= 0; i
< n
; i
++ )
179 // now we can compute our best size correctly, so do it if necessary
180 SetInitialSize(size
);
185 bool wxListBox::Create(wxWindow
*parent
,
189 const wxArrayString
& choices
,
191 const wxValidator
& validator
,
192 const wxString
& name
)
194 wxCArrayString
chs(choices
);
195 return Create(parent
, id
, pos
, size
, chs
.GetCount(), chs
.GetStrings(),
196 style
, validator
, name
);
199 wxListBox::~wxListBox()
204 WXDWORD
wxListBox::MSWGetStyle(long style
, WXDWORD
*exstyle
) const
206 WXDWORD msStyle
= wxControl::MSWGetStyle(style
, exstyle
);
208 // always show the vertical scrollbar if necessary -- otherwise it is
209 // impossible to use the control with the mouse
210 msStyle
|= WS_VSCROLL
;
212 // we always want to get the notifications
213 msStyle
|= LBS_NOTIFY
;
215 // without this style, you get unexpected heights, so e.g. constraint
216 // layout doesn't work properly
217 msStyle
|= LBS_NOINTEGRALHEIGHT
;
219 wxASSERT_MSG( !(style
& wxLB_MULTIPLE
) || !(style
& wxLB_EXTENDED
),
220 _T("only one of listbox selection modes can be specified") );
222 if ( style
& wxLB_MULTIPLE
)
223 msStyle
|= LBS_MULTIPLESEL
;
224 else if ( style
& wxLB_EXTENDED
)
225 msStyle
|= LBS_EXTENDEDSEL
;
227 if ( m_windowStyle
& wxLB_ALWAYS_SB
)
228 msStyle
|= LBS_DISABLENOSCROLL
;
229 if ( m_windowStyle
& wxLB_HSCROLL
)
230 msStyle
|= WS_HSCROLL
;
231 if ( m_windowStyle
& wxLB_SORT
)
234 #if wxUSE_OWNER_DRAWN && !defined(__WXWINCE__)
235 if ( m_windowStyle
& wxLB_OWNERDRAW
)
237 // we don't support LBS_OWNERDRAWVARIABLE yet and we also always put
238 // the strings in the listbox for simplicity even though we could have
239 // avoided it in this case
240 msStyle
|= LBS_OWNERDRAWFIXED
| LBS_HASSTRINGS
;
242 #endif // wxUSE_OWNER_DRAWN
247 // ----------------------------------------------------------------------------
248 // implementation of wxListBoxBase methods
249 // ----------------------------------------------------------------------------
251 void wxListBox::DoSetFirstItem(int N
)
253 wxCHECK_RET( IsValid(N
),
254 wxT("invalid index in wxListBox::SetFirstItem") );
256 SendMessage(GetHwnd(), LB_SETTOPINDEX
, (WPARAM
)N
, (LPARAM
)0);
259 void wxListBox::DoDeleteOneItem(unsigned int n
)
261 wxCHECK_RET( IsValid(n
),
262 wxT("invalid index in wxListBox::Delete") );
264 SendMessage(GetHwnd(), LB_DELETESTRING
, n
, 0);
267 SetHorizontalExtent(wxEmptyString
);
270 int wxListBox::FindString(const wxString
& s
, bool bCase
) const
272 // back to base class search for not native search type
274 return wxItemContainerImmutable::FindString( s
, bCase
);
276 int pos
= ListBox_FindStringExact(GetHwnd(), -1, s
.wx_str());
283 void wxListBox::DoClear()
287 ListBox_ResetContent(GetHwnd());
290 SetHorizontalExtent();
293 void wxListBox::Free()
295 #if wxUSE_OWNER_DRAWN
296 if ( m_windowStyle
& wxLB_OWNERDRAW
)
298 WX_CLEAR_ARRAY(m_aItems
);
300 #endif // wxUSE_OWNER_DRAWN
303 void wxListBox::DoSetSelection(int N
, bool select
)
305 wxCHECK_RET( N
== wxNOT_FOUND
|| IsValid(N
),
306 wxT("invalid index in wxListBox::SetSelection") );
308 if ( HasMultipleSelection() )
310 SendMessage(GetHwnd(), LB_SETSEL
, select
, N
);
314 SendMessage(GetHwnd(), LB_SETCURSEL
, select
? N
: -1, 0);
318 bool wxListBox::IsSelected(int N
) const
320 wxCHECK_MSG( IsValid(N
), false,
321 wxT("invalid index in wxListBox::Selected") );
323 return SendMessage(GetHwnd(), LB_GETSEL
, N
, 0) == 0 ? false : true;
326 void *wxListBox::DoGetItemClientData(unsigned int n
) const
328 wxCHECK_MSG( IsValid(n
), NULL
,
329 wxT("invalid index in wxListBox::GetClientData") );
331 return (void *)SendMessage(GetHwnd(), LB_GETITEMDATA
, n
, 0);
334 void wxListBox::DoSetItemClientData(unsigned int n
, void *clientData
)
336 wxCHECK_RET( IsValid(n
),
337 wxT("invalid index in wxListBox::SetClientData") );
339 #if wxUSE_OWNER_DRAWN
340 if ( m_windowStyle
& wxLB_OWNERDRAW
)
342 // client data must be pointer to wxOwnerDrawn, otherwise we would crash
343 // in OnMeasure/OnDraw.
344 wxFAIL_MSG(wxT("Can't use client data with owner-drawn listboxes"));
346 #endif // wxUSE_OWNER_DRAWN
348 if ( ListBox_SetItemData(GetHwnd(), n
, clientData
) == LB_ERR
)
349 wxLogDebug(wxT("LB_SETITEMDATA failed"));
352 // Return number of selections and an array of selected integers
353 int wxListBox::GetSelections(wxArrayInt
& aSelections
) const
357 if ( HasMultipleSelection() )
359 int countSel
= ListBox_GetSelCount(GetHwnd());
360 if ( countSel
== LB_ERR
)
362 wxLogDebug(_T("ListBox_GetSelCount failed"));
364 else if ( countSel
!= 0 )
366 int *selections
= new int[countSel
];
368 if ( ListBox_GetSelItems(GetHwnd(),
369 countSel
, selections
) == LB_ERR
)
371 wxLogDebug(wxT("ListBox_GetSelItems failed"));
376 aSelections
.Alloc(countSel
);
377 for ( int n
= 0; n
< countSel
; n
++ )
378 aSelections
.Add(selections
[n
]);
381 delete [] selections
;
386 else // single-selection listbox
388 if (ListBox_GetCurSel(GetHwnd()) > -1)
389 aSelections
.Add(ListBox_GetCurSel(GetHwnd()));
391 return aSelections
.Count();
395 // Get single selection, for single choice list items
396 int wxListBox::GetSelection() const
398 wxCHECK_MSG( !HasMultipleSelection(),
400 wxT("GetSelection() can't be used with multiple-selection listboxes, use GetSelections() instead.") );
402 return ListBox_GetCurSel(GetHwnd());
405 // Find string for position
406 wxString
wxListBox::GetString(unsigned int n
) const
408 wxCHECK_MSG( IsValid(n
), wxEmptyString
,
409 wxT("invalid index in wxListBox::GetString") );
411 int len
= ListBox_GetTextLen(GetHwnd(), n
);
413 // +1 for terminating NUL
415 ListBox_GetText(GetHwnd(), n
, (wxChar
*)wxStringBuffer(result
, len
+ 1));
420 int wxListBox::DoInsertItems(const wxArrayStringsAdapter
& items
,
423 wxClientDataType type
)
425 MSWAllocStorage(items
, LB_INITSTORAGE
);
427 const bool append
= pos
== GetCount();
429 // we must use CB_ADDSTRING when appending as only it works correctly for
430 // the sorted controls
431 const unsigned msg
= append
? LB_ADDSTRING
: LB_INSERTSTRING
;
438 const unsigned int numItems
= items
.GetCount();
439 for ( unsigned int i
= 0; i
< numItems
; i
++ )
441 n
= MSWInsertOrAppendItem(pos
, items
[i
], msg
);
442 if ( n
== wxNOT_FOUND
)
450 #if wxUSE_OWNER_DRAWN
451 if ( HasFlag(wxLB_OWNERDRAW
) )
453 wxOwnerDrawn
*pNewItem
= CreateLboxItem(n
);
454 pNewItem
->SetName(items
[i
]);
455 pNewItem
->SetFont(GetFont());
456 m_aItems
.Insert(pNewItem
, n
);
458 ListBox_SetItemData(GetHwnd(), n
, pNewItem
);
460 #endif // wxUSE_OWNER_DRAWN
461 AssignNewItemClientData(n
, clientData
, i
, type
);
464 SetHorizontalExtent();
469 int wxListBox::DoListHitTest(const wxPoint
& point
) const
471 LRESULT lRes
= ::SendMessage(GetHwnd(), LB_ITEMFROMPOINT
,
472 0L, MAKELONG(point
.x
, point
.y
));
474 // non zero high-order word means that this item is outside of the client
475 // area, IOW the point is outside of the listbox
476 return HIWORD(lRes
) ? wxNOT_FOUND
: lRes
;
479 void wxListBox::SetString(unsigned int n
, const wxString
& s
)
481 wxCHECK_RET( IsValid(n
),
482 wxT("invalid index in wxListBox::SetString") );
484 // remember the state of the item
485 bool wasSelected
= IsSelected(n
);
487 void *oldData
= NULL
;
488 wxClientData
*oldObjData
= NULL
;
489 if ( m_clientDataItemsType
== wxClientData_Void
)
490 oldData
= GetClientData(n
);
491 else if ( m_clientDataItemsType
== wxClientData_Object
)
492 oldObjData
= GetClientObject(n
);
494 // delete and recreate it
495 SendMessage(GetHwnd(), LB_DELETESTRING
, n
, 0);
498 if ( n
== (m_noItems
- 1) )
501 ListBox_InsertString(GetHwnd(), newN
, s
.wx_str());
503 // restore the client data
505 SetClientData(n
, oldData
);
506 else if ( oldObjData
)
507 SetClientObject(n
, oldObjData
);
509 #if wxUSE_OWNER_DRAWN
510 if ( m_windowStyle
& wxLB_OWNERDRAW
)
512 // update item's text
513 m_aItems
[n
]->SetName(s
);
515 // reassign the item's data
516 ListBox_SetItemData(GetHwnd(), n
, m_aItems
[n
]);
518 #endif //USE_OWNER_DRAWN
520 // we may have lost the selection
524 SetHorizontalExtent();
527 unsigned int wxListBox::GetCount() const
532 // ----------------------------------------------------------------------------
533 // size-related stuff
534 // ----------------------------------------------------------------------------
536 void wxListBox::SetHorizontalExtent(const wxString
& s
)
538 // in any case, our best size could have changed
539 InvalidateBestSize();
541 // the rest is only necessary if we want a horizontal scrollbar
542 if ( !HasFlag(wxHSCROLL
) )
546 WindowHDC
dc(GetHwnd());
547 SelectInHDC
selFont(dc
, GetHfontOf(GetFont()));
549 TEXTMETRIC lpTextMetric
;
550 ::GetTextMetrics(dc
, &lpTextMetric
);
552 int largestExtent
= 0;
557 // set extent to the max length of all strings
558 for ( unsigned int i
= 0; i
< m_noItems
; i
++ )
560 const wxString str
= GetString(i
);
561 ::GetTextExtentPoint32(dc
, str
.c_str(), str
.length(), &extentXY
);
563 int extentX
= (int)(extentXY
.cx
+ lpTextMetric
.tmAveCharWidth
);
564 if ( extentX
> largestExtent
)
565 largestExtent
= extentX
;
568 else // just increase the extent to the length of this string
570 int existingExtent
= (int)SendMessage(GetHwnd(),
571 LB_GETHORIZONTALEXTENT
, 0, 0L);
573 ::GetTextExtentPoint32(dc
, s
.c_str(), s
.length(), &extentXY
);
575 int extentX
= (int)(extentXY
.cx
+ lpTextMetric
.tmAveCharWidth
);
576 if ( extentX
> existingExtent
)
577 largestExtent
= extentX
;
581 SendMessage(GetHwnd(), LB_SETHORIZONTALEXTENT
, LOWORD(largestExtent
), 0L);
582 //else: it shouldn't change
585 wxSize
wxListBox::DoGetBestSize() const
587 // find the widest string
590 for (unsigned int i
= 0; i
< m_noItems
; i
++)
592 wxString
str(GetString(i
));
593 GetTextExtent(str
, &wLine
, NULL
);
594 if ( wLine
> wListbox
)
598 // give it some reasonable default value if there are no strings in the
603 // the listbox should be slightly larger than the widest string
605 wxGetCharSize(GetHWND(), &cx
, &cy
, GetFont());
609 // Add room for the scrollbar
610 wListbox
+= wxSystemSettings::GetMetric(wxSYS_VSCROLL_X
);
612 // don't make the listbox too tall (limit height to 10 items) but don't
613 // make it too small neither
614 int hListbox
= EDIT_HEIGHT_FROM_CHAR_HEIGHT(cy
)*
615 wxMin(wxMax(m_noItems
, 3), 10);
617 wxSize
best(wListbox
, hListbox
);
622 // ----------------------------------------------------------------------------
624 // ----------------------------------------------------------------------------
626 bool wxListBox::MSWCommand(WXUINT param
, WXWORD
WXUNUSED(id
))
629 if ( param
== LBN_SELCHANGE
)
631 evtType
= wxEVT_COMMAND_LISTBOX_SELECTED
;
633 else if ( param
== LBN_DBLCLK
)
635 evtType
= wxEVT_COMMAND_LISTBOX_DOUBLECLICKED
;
639 // some event we're not interested in
643 wxCommandEvent
event(evtType
, m_windowId
);
644 event
.SetEventObject( this );
646 // retrieve the affected item
647 int n
= SendMessage(GetHwnd(), LB_GETCARETINDEX
, 0, 0);
650 if ( HasClientObjectData() )
651 event
.SetClientObject( GetClientObject(n
) );
652 else if ( HasClientUntypedData() )
653 event
.SetClientData( GetClientData(n
) );
655 event
.SetString(GetString(n
));
656 event
.SetExtraLong( HasMultipleSelection() ? IsSelected(n
) : true );
661 return GetEventHandler()->ProcessEvent(event
);
664 // ----------------------------------------------------------------------------
665 // wxCheckListBox support
666 // ----------------------------------------------------------------------------
668 #if wxUSE_OWNER_DRAWN
673 // space beneath/above each row in pixels
674 // "standard" checklistbox use 1 here, some might prefer 2. 0 is ugly.
675 #define OWNER_DRAWN_LISTBOX_EXTRA_SPACE (1)
677 // the height is the same for all items
678 // TODO should be changed for LBS_OWNERDRAWVARIABLE style listboxes
680 // NB: can't forward this to wxListBoxItem because LB_SETITEMDATA
681 // message is not yet sent when we get here!
682 bool wxListBox::MSWOnMeasure(WXMEASUREITEMSTRUCT
*item
)
684 // only owner-drawn control should receive this message
685 wxCHECK( ((m_windowStyle
& wxLB_OWNERDRAW
) == wxLB_OWNERDRAW
), false );
687 MEASUREITEMSTRUCT
*pStruct
= (MEASUREITEMSTRUCT
*)item
;
690 HDC hdc
= GetDC(NULL
);
692 HDC hdc
= CreateIC(wxT("DISPLAY"), NULL
, NULL
, 0);
696 wxDCTemp
dc((WXHDC
)hdc
);
697 dc
.SetFont(GetFont());
699 pStruct
->itemHeight
= dc
.GetCharHeight() + 2*OWNER_DRAWN_LISTBOX_EXTRA_SPACE
;
700 pStruct
->itemWidth
= dc
.GetCharWidth();
704 ReleaseDC(NULL
, hdc
);
712 // forward the message to the appropriate item
713 bool wxListBox::MSWOnDraw(WXDRAWITEMSTRUCT
*item
)
715 // only owner-drawn control should receive this message
716 wxCHECK( ((m_windowStyle
& wxLB_OWNERDRAW
) == wxLB_OWNERDRAW
), false );
718 DRAWITEMSTRUCT
*pStruct
= (DRAWITEMSTRUCT
*)item
;
719 UINT itemID
= pStruct
->itemID
;
721 // the item may be -1 for an empty listbox
722 if ( itemID
== (UINT
)-1 )
725 LRESULT data
= ListBox_GetItemData(GetHwnd(), pStruct
->itemID
);
727 wxCHECK( data
&& (data
!= LB_ERR
), false );
729 wxListBoxItem
*pItem
= (wxListBoxItem
*)data
;
731 wxDCTemp
dc((WXHDC
)pStruct
->hDC
);
732 wxPoint
pt1(pStruct
->rcItem
.left
, pStruct
->rcItem
.top
);
733 wxPoint
pt2(pStruct
->rcItem
.right
, pStruct
->rcItem
.bottom
);
734 wxRect
rect(pt1
, pt2
);
736 return pItem
->OnDrawItem(dc
, rect
,
737 (wxOwnerDrawn::wxODAction
)pStruct
->itemAction
,
738 (wxOwnerDrawn::wxODStatus
)pStruct
->itemState
);
741 #endif // wxUSE_OWNER_DRAWN
743 #endif // wxUSE_LISTBOX