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"
35 #include "wx/msw/dc.h"
40 #include "wx/ownerdrw.h"
43 #if wxUSE_EXTENDED_RTTI
44 WX_DEFINE_FLAGS( wxListBoxStyle
)
46 wxBEGIN_FLAGS( wxListBoxStyle
)
47 // new style border flags, we put them first to
48 // use them for streaming out
49 wxFLAGS_MEMBER(wxBORDER_SIMPLE
)
50 wxFLAGS_MEMBER(wxBORDER_SUNKEN
)
51 wxFLAGS_MEMBER(wxBORDER_DOUBLE
)
52 wxFLAGS_MEMBER(wxBORDER_RAISED
)
53 wxFLAGS_MEMBER(wxBORDER_STATIC
)
54 wxFLAGS_MEMBER(wxBORDER_NONE
)
56 // old style border flags
57 wxFLAGS_MEMBER(wxSIMPLE_BORDER
)
58 wxFLAGS_MEMBER(wxSUNKEN_BORDER
)
59 wxFLAGS_MEMBER(wxDOUBLE_BORDER
)
60 wxFLAGS_MEMBER(wxRAISED_BORDER
)
61 wxFLAGS_MEMBER(wxSTATIC_BORDER
)
62 wxFLAGS_MEMBER(wxBORDER
)
64 // standard window styles
65 wxFLAGS_MEMBER(wxTAB_TRAVERSAL
)
66 wxFLAGS_MEMBER(wxCLIP_CHILDREN
)
67 wxFLAGS_MEMBER(wxTRANSPARENT_WINDOW
)
68 wxFLAGS_MEMBER(wxWANTS_CHARS
)
69 wxFLAGS_MEMBER(wxFULL_REPAINT_ON_RESIZE
)
70 wxFLAGS_MEMBER(wxALWAYS_SHOW_SB
)
71 wxFLAGS_MEMBER(wxVSCROLL
)
72 wxFLAGS_MEMBER(wxHSCROLL
)
74 wxFLAGS_MEMBER(wxLB_SINGLE
)
75 wxFLAGS_MEMBER(wxLB_MULTIPLE
)
76 wxFLAGS_MEMBER(wxLB_EXTENDED
)
77 wxFLAGS_MEMBER(wxLB_HSCROLL
)
78 wxFLAGS_MEMBER(wxLB_ALWAYS_SB
)
79 wxFLAGS_MEMBER(wxLB_NEEDED_SB
)
80 wxFLAGS_MEMBER(wxLB_SORT
)
82 wxEND_FLAGS( wxListBoxStyle
)
84 IMPLEMENT_DYNAMIC_CLASS_XTI(wxListBox
, wxControlWithItems
,"wx/listbox.h")
86 wxBEGIN_PROPERTIES_TABLE(wxListBox
)
87 wxEVENT_PROPERTY( Select
, wxEVT_COMMAND_LISTBOX_SELECTED
, wxCommandEvent
)
88 wxEVENT_PROPERTY( DoubleClick
, wxEVT_COMMAND_LISTBOX_DOUBLECLICKED
, wxCommandEvent
)
90 wxPROPERTY( Font
, wxFont
, SetFont
, GetFont
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group"))
91 wxPROPERTY_COLLECTION( Choices
, wxArrayString
, wxString
, AppendString
, GetStrings
, 0 /*flags*/ , wxT("Helpstring") , wxT("group") )
92 wxPROPERTY( Selection
,int, SetSelection
, GetSelection
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group") )
93 wxPROPERTY_FLAGS( WindowStyle
, wxListBoxStyle
, long , SetWindowStyleFlag
, GetWindowStyleFlag
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group")) // style
94 wxEND_PROPERTIES_TABLE()
96 wxBEGIN_HANDLERS_TABLE(wxListBox
)
97 wxEND_HANDLERS_TABLE()
99 wxCONSTRUCTOR_4( wxListBox
, wxWindow
* , Parent
, wxWindowID
, Id
, wxPoint
, Position
, wxSize
, Size
)
101 IMPLEMENT_DYNAMIC_CLASS(wxListBox
, wxControlWithItems
)
111 // ============================================================================
112 // list box item declaration and implementation
113 // ============================================================================
115 #if wxUSE_OWNER_DRAWN
117 class wxListBoxItem
: public wxOwnerDrawn
120 wxListBoxItem(const wxString
& str
= wxEmptyString
);
123 wxListBoxItem::wxListBoxItem(const wxString
& str
) : wxOwnerDrawn(str
, false)
125 // no bitmaps/checkmarks
129 wxOwnerDrawn
*wxListBox::CreateLboxItem(size_t WXUNUSED(n
))
131 return new wxListBoxItem();
134 #endif //USE_OWNER_DRAWN
136 // ============================================================================
137 // list box control implementation
138 // ============================================================================
140 // ----------------------------------------------------------------------------
142 // ----------------------------------------------------------------------------
145 wxListBox::wxListBox()
151 bool wxListBox::Create(wxWindow
*parent
,
155 int n
, const wxString choices
[],
157 const wxValidator
& validator
,
158 const wxString
& name
)
163 // initialize base class fields
164 if ( !CreateControl(parent
, id
, pos
, size
, style
, validator
, name
) )
167 // create the native control
168 if ( !MSWCreateControl(_T("LISTBOX"), wxEmptyString
, pos
, size
) )
170 // control creation failed
174 // initialize the contents
175 for ( int i
= 0; i
< n
; i
++ )
180 // now we can compute our best size correctly, so do it if necessary
181 SetInitialSize(size
);
186 bool wxListBox::Create(wxWindow
*parent
,
190 const wxArrayString
& choices
,
192 const wxValidator
& validator
,
193 const wxString
& name
)
195 wxCArrayString
chs(choices
);
196 return Create(parent
, id
, pos
, size
, chs
.GetCount(), chs
.GetStrings(),
197 style
, validator
, name
);
200 wxListBox::~wxListBox()
205 WXDWORD
wxListBox::MSWGetStyle(long style
, WXDWORD
*exstyle
) const
207 WXDWORD msStyle
= wxControl::MSWGetStyle(style
, exstyle
);
209 // always show the vertical scrollbar if necessary -- otherwise it is
210 // impossible to use the control with the mouse
211 msStyle
|= WS_VSCROLL
;
213 // we always want to get the notifications
214 msStyle
|= LBS_NOTIFY
;
216 // without this style, you get unexpected heights, so e.g. constraint
217 // layout doesn't work properly
218 msStyle
|= LBS_NOINTEGRALHEIGHT
;
220 wxASSERT_MSG( !(style
& wxLB_MULTIPLE
) || !(style
& wxLB_EXTENDED
),
221 _T("only one of listbox selection modes can be specified") );
223 if ( style
& wxLB_MULTIPLE
)
224 msStyle
|= LBS_MULTIPLESEL
;
225 else if ( style
& wxLB_EXTENDED
)
226 msStyle
|= LBS_EXTENDEDSEL
;
228 if ( m_windowStyle
& wxLB_ALWAYS_SB
)
229 msStyle
|= LBS_DISABLENOSCROLL
;
230 if ( m_windowStyle
& wxLB_HSCROLL
)
231 msStyle
|= WS_HSCROLL
;
232 if ( m_windowStyle
& wxLB_SORT
)
235 #if wxUSE_OWNER_DRAWN && !defined(__WXWINCE__)
236 if ( m_windowStyle
& wxLB_OWNERDRAW
)
238 // we don't support LBS_OWNERDRAWVARIABLE yet and we also always put
239 // the strings in the listbox for simplicity even though we could have
240 // avoided it in this case
241 msStyle
|= LBS_OWNERDRAWFIXED
| LBS_HASSTRINGS
;
243 #endif // wxUSE_OWNER_DRAWN
248 // ----------------------------------------------------------------------------
249 // implementation of wxListBoxBase methods
250 // ----------------------------------------------------------------------------
252 void wxListBox::DoSetFirstItem(int N
)
254 wxCHECK_RET( IsValid(N
),
255 wxT("invalid index in wxListBox::SetFirstItem") );
257 SendMessage(GetHwnd(), LB_SETTOPINDEX
, (WPARAM
)N
, (LPARAM
)0);
260 void wxListBox::DoDeleteOneItem(unsigned int n
)
262 wxCHECK_RET( IsValid(n
),
263 wxT("invalid index in wxListBox::Delete") );
265 SendMessage(GetHwnd(), LB_DELETESTRING
, n
, 0);
268 SetHorizontalExtent(wxEmptyString
);
270 UpdateOldSelections();
273 int wxListBox::FindString(const wxString
& s
, bool bCase
) const
275 // back to base class search for not native search type
277 return wxItemContainerImmutable::FindString( s
, bCase
);
279 int pos
= ListBox_FindStringExact(GetHwnd(), -1, s
.wx_str());
286 void wxListBox::DoClear()
290 ListBox_ResetContent(GetHwnd());
293 SetHorizontalExtent();
295 UpdateOldSelections();
298 void wxListBox::Free()
300 #if wxUSE_OWNER_DRAWN
301 if ( m_windowStyle
& wxLB_OWNERDRAW
)
303 WX_CLEAR_ARRAY(m_aItems
);
305 #endif // wxUSE_OWNER_DRAWN
308 void wxListBox::DoSetSelection(int N
, bool select
)
310 wxCHECK_RET( N
== wxNOT_FOUND
|| IsValid(N
),
311 wxT("invalid index in wxListBox::SetSelection") );
313 if ( HasMultipleSelection() )
315 SendMessage(GetHwnd(), LB_SETSEL
, select
, N
);
319 SendMessage(GetHwnd(), LB_SETCURSEL
, select
? N
: -1, 0);
322 UpdateOldSelections();
325 bool wxListBox::IsSelected(int N
) const
327 wxCHECK_MSG( IsValid(N
), false,
328 wxT("invalid index in wxListBox::Selected") );
330 return SendMessage(GetHwnd(), LB_GETSEL
, N
, 0) == 0 ? false : true;
333 void *wxListBox::DoGetItemClientData(unsigned int n
) const
335 wxCHECK_MSG( IsValid(n
), NULL
,
336 wxT("invalid index in wxListBox::GetClientData") );
338 return (void *)SendMessage(GetHwnd(), LB_GETITEMDATA
, n
, 0);
341 void wxListBox::DoSetItemClientData(unsigned int n
, void *clientData
)
343 wxCHECK_RET( IsValid(n
),
344 wxT("invalid index in wxListBox::SetClientData") );
346 #if wxUSE_OWNER_DRAWN
347 if ( m_windowStyle
& wxLB_OWNERDRAW
)
349 // client data must be pointer to wxOwnerDrawn, otherwise we would crash
350 // in OnMeasure/OnDraw.
351 wxFAIL_MSG(wxT("Can't use client data with owner-drawn listboxes"));
353 #endif // wxUSE_OWNER_DRAWN
355 if ( ListBox_SetItemData(GetHwnd(), n
, clientData
) == LB_ERR
)
356 wxLogDebug(wxT("LB_SETITEMDATA failed"));
359 // Return number of selections and an array of selected integers
360 int wxListBox::GetSelections(wxArrayInt
& aSelections
) const
364 if ( HasMultipleSelection() )
366 int countSel
= ListBox_GetSelCount(GetHwnd());
367 if ( countSel
== LB_ERR
)
369 wxLogDebug(_T("ListBox_GetSelCount failed"));
371 else if ( countSel
!= 0 )
373 int *selections
= new int[countSel
];
375 if ( ListBox_GetSelItems(GetHwnd(),
376 countSel
, selections
) == LB_ERR
)
378 wxLogDebug(wxT("ListBox_GetSelItems failed"));
383 aSelections
.Alloc(countSel
);
384 for ( int n
= 0; n
< countSel
; n
++ )
385 aSelections
.Add(selections
[n
]);
388 delete [] selections
;
393 else // single-selection listbox
395 if (ListBox_GetCurSel(GetHwnd()) > -1)
396 aSelections
.Add(ListBox_GetCurSel(GetHwnd()));
398 return aSelections
.Count();
402 // Get single selection, for single choice list items
403 int wxListBox::GetSelection() const
405 wxCHECK_MSG( !HasMultipleSelection(),
407 wxT("GetSelection() can't be used with multiple-selection listboxes, use GetSelections() instead.") );
409 return ListBox_GetCurSel(GetHwnd());
412 // Find string for position
413 wxString
wxListBox::GetString(unsigned int n
) const
415 wxCHECK_MSG( IsValid(n
), wxEmptyString
,
416 wxT("invalid index in wxListBox::GetString") );
418 int len
= ListBox_GetTextLen(GetHwnd(), n
);
420 // +1 for terminating NUL
422 ListBox_GetText(GetHwnd(), n
, (wxChar
*)wxStringBuffer(result
, len
+ 1));
427 int wxListBox::DoInsertItems(const wxArrayStringsAdapter
& items
,
430 wxClientDataType type
)
432 MSWAllocStorage(items
, LB_INITSTORAGE
);
434 const bool append
= pos
== GetCount();
436 // we must use CB_ADDSTRING when appending as only it works correctly for
437 // the sorted controls
438 const unsigned msg
= append
? LB_ADDSTRING
: LB_INSERTSTRING
;
445 const unsigned int numItems
= items
.GetCount();
446 for ( unsigned int i
= 0; i
< numItems
; i
++ )
448 n
= MSWInsertOrAppendItem(pos
, items
[i
], msg
);
449 if ( n
== wxNOT_FOUND
)
457 #if wxUSE_OWNER_DRAWN
458 if ( HasFlag(wxLB_OWNERDRAW
) )
460 wxOwnerDrawn
*pNewItem
= CreateLboxItem(n
);
461 pNewItem
->SetName(items
[i
]);
462 pNewItem
->SetFont(GetFont());
463 m_aItems
.Insert(pNewItem
, n
);
465 ListBox_SetItemData(GetHwnd(), n
, pNewItem
);
467 #endif // wxUSE_OWNER_DRAWN
468 AssignNewItemClientData(n
, clientData
, i
, type
);
471 SetHorizontalExtent();
473 UpdateOldSelections();
478 int wxListBox::DoListHitTest(const wxPoint
& point
) const
480 LRESULT lRes
= ::SendMessage(GetHwnd(), LB_ITEMFROMPOINT
,
481 0L, MAKELONG(point
.x
, point
.y
));
483 // non zero high-order word means that this item is outside of the client
484 // area, IOW the point is outside of the listbox
485 return HIWORD(lRes
) ? wxNOT_FOUND
: lRes
;
488 void wxListBox::SetString(unsigned int n
, const wxString
& s
)
490 wxCHECK_RET( IsValid(n
),
491 wxT("invalid index in wxListBox::SetString") );
493 // remember the state of the item
494 bool wasSelected
= IsSelected(n
);
496 void *oldData
= NULL
;
497 wxClientData
*oldObjData
= NULL
;
498 if ( HasClientUntypedData() )
499 oldData
= GetClientData(n
);
500 else if ( HasClientObjectData() )
501 oldObjData
= GetClientObject(n
);
503 // delete and recreate it
504 SendMessage(GetHwnd(), LB_DELETESTRING
, n
, 0);
507 if ( n
== (m_noItems
- 1) )
510 ListBox_InsertString(GetHwnd(), newN
, s
.wx_str());
512 // restore the client data
514 SetClientData(n
, oldData
);
515 else if ( oldObjData
)
516 SetClientObject(n
, oldObjData
);
518 #if wxUSE_OWNER_DRAWN
519 if ( m_windowStyle
& wxLB_OWNERDRAW
)
521 // update item's text
522 m_aItems
[n
]->SetName(s
);
524 // reassign the item's data
525 ListBox_SetItemData(GetHwnd(), n
, m_aItems
[n
]);
527 #endif //USE_OWNER_DRAWN
529 // we may have lost the selection
533 SetHorizontalExtent();
536 unsigned int wxListBox::GetCount() const
541 // ----------------------------------------------------------------------------
542 // size-related stuff
543 // ----------------------------------------------------------------------------
545 void wxListBox::SetHorizontalExtent(const wxString
& s
)
547 // in any case, our best size could have changed
548 InvalidateBestSize();
550 // the rest is only necessary if we want a horizontal scrollbar
551 if ( !HasFlag(wxHSCROLL
) )
555 WindowHDC
dc(GetHwnd());
556 SelectInHDC
selFont(dc
, GetHfontOf(GetFont()));
558 TEXTMETRIC lpTextMetric
;
559 ::GetTextMetrics(dc
, &lpTextMetric
);
561 int largestExtent
= 0;
566 // set extent to the max length of all strings
567 for ( unsigned int i
= 0; i
< m_noItems
; i
++ )
569 const wxString str
= GetString(i
);
570 ::GetTextExtentPoint32(dc
, str
.c_str(), str
.length(), &extentXY
);
572 int extentX
= (int)(extentXY
.cx
+ lpTextMetric
.tmAveCharWidth
);
573 if ( extentX
> largestExtent
)
574 largestExtent
= extentX
;
577 else // just increase the extent to the length of this string
579 int existingExtent
= (int)SendMessage(GetHwnd(),
580 LB_GETHORIZONTALEXTENT
, 0, 0L);
582 ::GetTextExtentPoint32(dc
, s
.c_str(), s
.length(), &extentXY
);
584 int extentX
= (int)(extentXY
.cx
+ lpTextMetric
.tmAveCharWidth
);
585 if ( extentX
> existingExtent
)
586 largestExtent
= extentX
;
590 SendMessage(GetHwnd(), LB_SETHORIZONTALEXTENT
, LOWORD(largestExtent
), 0L);
591 //else: it shouldn't change
594 wxSize
wxListBox::DoGetBestSize() const
596 // find the widest string
599 for (unsigned int i
= 0; i
< m_noItems
; i
++)
601 wxString
str(GetString(i
));
602 GetTextExtent(str
, &wLine
, NULL
);
603 if ( wLine
> wListbox
)
607 // give it some reasonable default value if there are no strings in the
612 // the listbox should be slightly larger than the widest string
614 wxGetCharSize(GetHWND(), &cx
, &cy
, GetFont());
618 // Add room for the scrollbar
619 wListbox
+= wxSystemSettings::GetMetric(wxSYS_VSCROLL_X
);
621 // don't make the listbox too tall (limit height to 10 items) but don't
622 // make it too small neither
623 int hListbox
= EDIT_HEIGHT_FROM_CHAR_HEIGHT(cy
)*
624 wxMin(wxMax(m_noItems
, 3), 10);
626 wxSize
best(wListbox
, hListbox
);
631 // ----------------------------------------------------------------------------
633 // ----------------------------------------------------------------------------
635 bool wxListBox::MSWCommand(WXUINT param
, WXWORD
WXUNUSED(id
))
637 if ((param
== LBN_SELCHANGE
) && HasMultipleSelection())
644 if ( param
== LBN_SELCHANGE
)
646 evtType
= wxEVT_COMMAND_LISTBOX_SELECTED
;
648 else if ( param
== LBN_DBLCLK
)
650 evtType
= wxEVT_COMMAND_LISTBOX_DOUBLECLICKED
;
654 // some event we're not interested in
658 wxCommandEvent
event(evtType
, m_windowId
);
659 event
.SetEventObject( this );
661 // retrieve the affected item
662 int n
= SendMessage(GetHwnd(), LB_GETCARETINDEX
, 0, 0);
665 if ( HasClientObjectData() )
666 event
.SetClientObject( GetClientObject(n
) );
667 else if ( HasClientUntypedData() )
668 event
.SetClientData( GetClientData(n
) );
670 event
.SetString(GetString(n
));
679 return HandleWindowEvent(event
);
682 // ----------------------------------------------------------------------------
683 // wxCheckListBox support
684 // ----------------------------------------------------------------------------
686 #if wxUSE_OWNER_DRAWN
691 // space beneath/above each row in pixels
692 // "standard" checklistbox use 1 here, some might prefer 2. 0 is ugly.
693 #define OWNER_DRAWN_LISTBOX_EXTRA_SPACE (1)
695 // the height is the same for all items
696 // TODO should be changed for LBS_OWNERDRAWVARIABLE style listboxes
698 // NB: can't forward this to wxListBoxItem because LB_SETITEMDATA
699 // message is not yet sent when we get here!
700 bool wxListBox::MSWOnMeasure(WXMEASUREITEMSTRUCT
*item
)
702 // only owner-drawn control should receive this message
703 wxCHECK( ((m_windowStyle
& wxLB_OWNERDRAW
) == wxLB_OWNERDRAW
), false );
705 MEASUREITEMSTRUCT
*pStruct
= (MEASUREITEMSTRUCT
*)item
;
708 HDC hdc
= GetDC(NULL
);
710 HDC hdc
= CreateIC(wxT("DISPLAY"), NULL
, NULL
, 0);
714 wxDCTemp
dc((WXHDC
)hdc
);
715 dc
.SetFont(GetFont());
717 pStruct
->itemHeight
= dc
.GetCharHeight() + 2*OWNER_DRAWN_LISTBOX_EXTRA_SPACE
;
718 pStruct
->itemWidth
= dc
.GetCharWidth();
722 ReleaseDC(NULL
, hdc
);
730 // forward the message to the appropriate item
731 bool wxListBox::MSWOnDraw(WXDRAWITEMSTRUCT
*item
)
733 // only owner-drawn control should receive this message
734 wxCHECK( ((m_windowStyle
& wxLB_OWNERDRAW
) == wxLB_OWNERDRAW
), false );
736 DRAWITEMSTRUCT
*pStruct
= (DRAWITEMSTRUCT
*)item
;
737 UINT itemID
= pStruct
->itemID
;
739 // the item may be -1 for an empty listbox
740 if ( itemID
== (UINT
)-1 )
743 LRESULT data
= ListBox_GetItemData(GetHwnd(), pStruct
->itemID
);
745 wxCHECK( data
&& (data
!= LB_ERR
), false );
747 wxListBoxItem
*pItem
= (wxListBoxItem
*)data
;
749 wxDCTemp
dc((WXHDC
)pStruct
->hDC
);
750 wxPoint
pt1(pStruct
->rcItem
.left
, pStruct
->rcItem
.top
);
751 wxPoint
pt2(pStruct
->rcItem
.right
, pStruct
->rcItem
.bottom
);
752 wxRect
rect(pt1
, pt2
);
754 return pItem
->OnDrawItem(dc
, rect
,
755 (wxOwnerDrawn::wxODAction
)pStruct
->itemAction
,
756 (wxOwnerDrawn::wxODStatus
)pStruct
->itemState
);
759 #endif // wxUSE_OWNER_DRAWN
761 #endif // wxUSE_LISTBOX