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_NO_SB
)
81 wxFLAGS_MEMBER(wxLB_SORT
)
83 wxEND_FLAGS( wxListBoxStyle
)
85 IMPLEMENT_DYNAMIC_CLASS_XTI(wxListBox
, wxControlWithItems
,"wx/listbox.h")
87 wxBEGIN_PROPERTIES_TABLE(wxListBox
)
88 wxEVENT_PROPERTY( Select
, wxEVT_COMMAND_LISTBOX_SELECTED
, wxCommandEvent
)
89 wxEVENT_PROPERTY( DoubleClick
, wxEVT_COMMAND_LISTBOX_DOUBLECLICKED
, wxCommandEvent
)
91 wxPROPERTY( Font
, wxFont
, SetFont
, GetFont
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group"))
92 wxPROPERTY_COLLECTION( Choices
, wxArrayString
, wxString
, AppendString
, GetStrings
, 0 /*flags*/ , wxT("Helpstring") , wxT("group") )
93 wxPROPERTY( Selection
,int, SetSelection
, GetSelection
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group") )
94 wxPROPERTY_FLAGS( WindowStyle
, wxListBoxStyle
, long , SetWindowStyleFlag
, GetWindowStyleFlag
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group")) // style
95 wxEND_PROPERTIES_TABLE()
97 wxBEGIN_HANDLERS_TABLE(wxListBox
)
98 wxEND_HANDLERS_TABLE()
100 wxCONSTRUCTOR_4( wxListBox
, wxWindow
* , Parent
, wxWindowID
, Id
, wxPoint
, Position
, wxSize
, Size
)
102 IMPLEMENT_DYNAMIC_CLASS(wxListBox
, wxControlWithItems
)
112 // ============================================================================
113 // list box item declaration and implementation
114 // ============================================================================
116 #if wxUSE_OWNER_DRAWN
118 class wxListBoxItem
: public wxOwnerDrawn
121 wxListBoxItem(wxListBox
*parent
)
122 { m_parent
= parent
; }
124 wxListBox
*GetParent() const
128 { return m_parent
->GetItemIndex(const_cast<wxListBoxItem
*>(this)); }
130 wxString
GetName() const
131 { return m_parent
->GetString(GetIndex()); }
137 wxOwnerDrawn
*wxListBox::CreateLboxItem(size_t WXUNUSED(n
))
139 return new wxListBoxItem(this);
142 #endif //USE_OWNER_DRAWN
144 // ============================================================================
145 // list box control implementation
146 // ============================================================================
148 // ----------------------------------------------------------------------------
150 // ----------------------------------------------------------------------------
153 wxListBox::wxListBox()
156 m_updateHorizontalExtent
= false;
159 bool wxListBox::Create(wxWindow
*parent
,
163 int n
, const wxString choices
[],
165 const wxValidator
& validator
,
166 const wxString
& name
)
169 m_updateHorizontalExtent
= false;
171 // initialize base class fields
172 if ( !CreateControl(parent
, id
, pos
, size
, style
, validator
, name
) )
175 // create the native control
176 if ( !MSWCreateControl(wxT("LISTBOX"), wxEmptyString
, pos
, size
) )
178 // control creation failed
182 // initialize the contents
183 for ( int i
= 0; i
< n
; i
++ )
188 // now we can compute our best size correctly, so do it again
189 SetInitialSize(size
);
194 bool wxListBox::Create(wxWindow
*parent
,
198 const wxArrayString
& choices
,
200 const wxValidator
& validator
,
201 const wxString
& name
)
203 wxCArrayString
chs(choices
);
204 return Create(parent
, id
, pos
, size
, chs
.GetCount(), chs
.GetStrings(),
205 style
, validator
, name
);
208 wxListBox::~wxListBox()
213 WXDWORD
wxListBox::MSWGetStyle(long style
, WXDWORD
*exstyle
) const
215 WXDWORD msStyle
= wxControl::MSWGetStyle(style
, exstyle
);
217 // we always want to get the notifications
218 msStyle
|= LBS_NOTIFY
;
220 // without this style, you get unexpected heights, so e.g. constraint
221 // layout doesn't work properly
222 msStyle
|= LBS_NOINTEGRALHEIGHT
;
224 wxASSERT_MSG( !(style
& wxLB_MULTIPLE
) || !(style
& wxLB_EXTENDED
),
225 wxT("only one of listbox selection modes can be specified") );
227 if ( style
& wxLB_MULTIPLE
)
228 msStyle
|= LBS_MULTIPLESEL
;
229 else if ( style
& wxLB_EXTENDED
)
230 msStyle
|= LBS_EXTENDEDSEL
;
232 wxASSERT_MSG( !(style
& wxLB_ALWAYS_SB
) || !(style
& wxLB_NO_SB
),
233 wxT( "Conflicting styles wxLB_ALWAYS_SB and wxLB_NO_SB." ) );
235 if ( !(style
& wxLB_NO_SB
) )
237 msStyle
|= WS_VSCROLL
;
238 if ( style
& wxLB_ALWAYS_SB
)
239 msStyle
|= LBS_DISABLENOSCROLL
;
242 if ( m_windowStyle
& wxLB_HSCROLL
)
243 msStyle
|= WS_HSCROLL
;
244 if ( m_windowStyle
& wxLB_SORT
)
247 #if wxUSE_OWNER_DRAWN && !defined(__WXWINCE__)
248 if ( m_windowStyle
& wxLB_OWNERDRAW
)
250 // we don't support LBS_OWNERDRAWVARIABLE yet and we also always put
251 // the strings in the listbox for simplicity even though we could have
252 // avoided it in this case
253 msStyle
|= LBS_OWNERDRAWFIXED
| LBS_HASSTRINGS
;
255 #endif // wxUSE_OWNER_DRAWN
260 void wxListBox::OnInternalIdle()
262 wxWindow::OnInternalIdle();
264 if (m_updateHorizontalExtent
)
266 SetHorizontalExtent(wxEmptyString
);
267 m_updateHorizontalExtent
= false;
271 void wxListBox::MSWOnItemsChanged()
273 // we need to do two things when items change: update their max horizontal
274 // extent so that horizontal scrollbar could be shown or hidden as
275 // appropriate and also invlaidate the best size
277 // updating the max extent is slow (it's an O(N) operation) and so we defer
278 // it until the idle time but the best size should be invalidated
279 // immediately doing it in idle time is too late -- layout using incorrect
280 // old best size will have been already done by then
282 m_updateHorizontalExtent
= true;
284 InvalidateBestSize();
287 // ----------------------------------------------------------------------------
288 // implementation of wxListBoxBase methods
289 // ----------------------------------------------------------------------------
291 void wxListBox::DoSetFirstItem(int N
)
293 wxCHECK_RET( IsValid(N
),
294 wxT("invalid index in wxListBox::SetFirstItem") );
296 SendMessage(GetHwnd(), LB_SETTOPINDEX
, (WPARAM
)N
, (LPARAM
)0);
299 void wxListBox::DoDeleteOneItem(unsigned int n
)
301 wxCHECK_RET( IsValid(n
),
302 wxT("invalid index in wxListBox::Delete") );
304 #if wxUSE_OWNER_DRAWN
305 if ( HasFlag(wxLB_OWNERDRAW
) )
308 m_aItems
.RemoveAt(n
);
310 #endif // wxUSE_OWNER_DRAWN
312 SendMessage(GetHwnd(), LB_DELETESTRING
, n
, 0);
317 UpdateOldSelections();
320 int wxListBox::FindString(const wxString
& s
, bool bCase
) const
322 // back to base class search for not native search type
324 return wxItemContainerImmutable::FindString( s
, bCase
);
326 int pos
= ListBox_FindStringExact(GetHwnd(), -1, s
.wx_str());
333 void wxListBox::DoClear()
335 #if wxUSE_OWNER_DRAWN
336 if ( HasFlag(wxLB_OWNERDRAW
) )
338 WX_CLEAR_ARRAY(m_aItems
);
340 #endif // wxUSE_OWNER_DRAWN
342 ListBox_ResetContent(GetHwnd());
347 UpdateOldSelections();
350 void wxListBox::DoSetSelection(int N
, bool select
)
352 wxCHECK_RET( N
== wxNOT_FOUND
|| IsValid(N
),
353 wxT("invalid index in wxListBox::SetSelection") );
355 if ( HasMultipleSelection() )
357 SendMessage(GetHwnd(), LB_SETSEL
, select
, N
);
361 SendMessage(GetHwnd(), LB_SETCURSEL
, select
? N
: -1, 0);
364 UpdateOldSelections();
367 bool wxListBox::IsSelected(int N
) const
369 wxCHECK_MSG( IsValid(N
), false,
370 wxT("invalid index in wxListBox::Selected") );
372 return SendMessage(GetHwnd(), LB_GETSEL
, N
, 0) == 0 ? false : true;
375 void *wxListBox::DoGetItemClientData(unsigned int n
) const
377 wxCHECK_MSG( IsValid(n
), NULL
,
378 wxT("invalid index in wxListBox::GetClientData") );
380 return (void *)SendMessage(GetHwnd(), LB_GETITEMDATA
, n
, 0);
383 void wxListBox::DoSetItemClientData(unsigned int n
, void *clientData
)
385 wxCHECK_RET( IsValid(n
),
386 wxT("invalid index in wxListBox::SetClientData") );
388 if ( ListBox_SetItemData(GetHwnd(), n
, clientData
) == LB_ERR
)
390 wxLogDebug(wxT("LB_SETITEMDATA failed"));
394 // Return number of selections and an array of selected integers
395 int wxListBox::GetSelections(wxArrayInt
& aSelections
) const
399 if ( HasMultipleSelection() )
401 int countSel
= ListBox_GetSelCount(GetHwnd());
402 if ( countSel
== LB_ERR
)
404 wxLogDebug(wxT("ListBox_GetSelCount failed"));
406 else if ( countSel
!= 0 )
408 int *selections
= new int[countSel
];
410 if ( ListBox_GetSelItems(GetHwnd(),
411 countSel
, selections
) == LB_ERR
)
413 wxLogDebug(wxT("ListBox_GetSelItems failed"));
418 aSelections
.Alloc(countSel
);
419 for ( int n
= 0; n
< countSel
; n
++ )
420 aSelections
.Add(selections
[n
]);
423 delete [] selections
;
428 else // single-selection listbox
430 if (ListBox_GetCurSel(GetHwnd()) > -1)
431 aSelections
.Add(ListBox_GetCurSel(GetHwnd()));
433 return aSelections
.Count();
437 // Get single selection, for single choice list items
438 int wxListBox::GetSelection() const
440 wxCHECK_MSG( !HasMultipleSelection(),
442 wxT("GetSelection() can't be used with multiple-selection listboxes, use GetSelections() instead.") );
444 return ListBox_GetCurSel(GetHwnd());
447 // Find string for position
448 wxString
wxListBox::GetString(unsigned int n
) const
450 wxCHECK_MSG( IsValid(n
), wxEmptyString
,
451 wxT("invalid index in wxListBox::GetString") );
453 int len
= ListBox_GetTextLen(GetHwnd(), n
);
455 // +1 for terminating NUL
457 ListBox_GetText(GetHwnd(), n
, (wxChar
*)wxStringBuffer(result
, len
+ 1));
462 int wxListBox::DoInsertItems(const wxArrayStringsAdapter
& items
,
465 wxClientDataType type
)
467 MSWAllocStorage(items
, LB_INITSTORAGE
);
469 const bool append
= pos
== GetCount();
471 // we must use CB_ADDSTRING when appending as only it works correctly for
472 // the sorted controls
473 const unsigned msg
= append
? LB_ADDSTRING
: LB_INSERTSTRING
;
480 const unsigned int numItems
= items
.GetCount();
481 for ( unsigned int i
= 0; i
< numItems
; i
++ )
483 n
= MSWInsertOrAppendItem(pos
, items
[i
], msg
);
484 if ( n
== wxNOT_FOUND
)
492 #if wxUSE_OWNER_DRAWN
493 if ( HasFlag(wxLB_OWNERDRAW
) )
495 wxOwnerDrawn
*pNewItem
= CreateLboxItem(n
);
496 pNewItem
->SetFont(GetFont());
497 m_aItems
.Insert(pNewItem
, n
);
499 #endif // wxUSE_OWNER_DRAWN
500 AssignNewItemClientData(n
, clientData
, i
, type
);
505 UpdateOldSelections();
510 int wxListBox::DoHitTestList(const wxPoint
& point
) const
512 LRESULT lRes
= ::SendMessage(GetHwnd(), LB_ITEMFROMPOINT
,
513 0, MAKELPARAM(point
.x
, point
.y
));
515 // non zero high-order word means that this item is outside of the client
516 // area, IOW the point is outside of the listbox
517 return HIWORD(lRes
) ? wxNOT_FOUND
: LOWORD(lRes
);
520 void wxListBox::SetString(unsigned int n
, const wxString
& s
)
522 wxCHECK_RET( IsValid(n
),
523 wxT("invalid index in wxListBox::SetString") );
525 // remember the state of the item
526 bool wasSelected
= IsSelected(n
);
528 void *oldData
= NULL
;
529 wxClientData
*oldObjData
= NULL
;
530 if ( HasClientUntypedData() )
531 oldData
= GetClientData(n
);
532 else if ( HasClientObjectData() )
533 oldObjData
= GetClientObject(n
);
535 // delete and recreate it
536 SendMessage(GetHwnd(), LB_DELETESTRING
, n
, 0);
539 if ( n
== (m_noItems
- 1) )
542 ListBox_InsertString(GetHwnd(), newN
, s
.wx_str());
544 // restore the client data
546 SetClientData(n
, oldData
);
547 else if ( oldObjData
)
548 SetClientObject(n
, oldObjData
);
550 // we may have lost the selection
557 unsigned int wxListBox::GetCount() const
562 // ----------------------------------------------------------------------------
563 // size-related stuff
564 // ----------------------------------------------------------------------------
566 void wxListBox::SetHorizontalExtent(const wxString
& s
)
568 // the rest is only necessary if we want a horizontal scrollbar
569 if ( !HasFlag(wxHSCROLL
) )
573 WindowHDC
dc(GetHwnd());
574 SelectInHDC
selFont(dc
, GetHfontOf(GetFont()));
576 TEXTMETRIC lpTextMetric
;
577 ::GetTextMetrics(dc
, &lpTextMetric
);
579 int largestExtent
= 0;
584 // set extent to the max length of all strings
585 for ( unsigned int i
= 0; i
< m_noItems
; i
++ )
587 const wxString str
= GetString(i
);
588 ::GetTextExtentPoint32(dc
, str
.c_str(), str
.length(), &extentXY
);
590 int extentX
= (int)(extentXY
.cx
+ lpTextMetric
.tmAveCharWidth
);
591 if ( extentX
> largestExtent
)
592 largestExtent
= extentX
;
595 else // just increase the extent to the length of this string
597 int existingExtent
= (int)SendMessage(GetHwnd(),
598 LB_GETHORIZONTALEXTENT
, 0, 0L);
600 ::GetTextExtentPoint32(dc
, s
.c_str(), s
.length(), &extentXY
);
602 int extentX
= (int)(extentXY
.cx
+ lpTextMetric
.tmAveCharWidth
);
603 if ( extentX
> existingExtent
)
604 largestExtent
= extentX
;
608 SendMessage(GetHwnd(), LB_SETHORIZONTALEXTENT
, LOWORD(largestExtent
), 0L);
609 //else: it shouldn't change
612 wxSize
wxListBox::DoGetBestClientSize() const
614 // find the widest string
617 for (unsigned int i
= 0; i
< m_noItems
; i
++)
619 wxString
str(GetString(i
));
620 GetTextExtent(str
, &wLine
, NULL
);
621 if ( wLine
> wListbox
)
625 // give it some reasonable default value if there are no strings in the
630 // the listbox should be slightly larger than the widest string
631 wListbox
+= 3*GetCharWidth();
633 // add room for the scrollbar
634 wListbox
+= wxSystemSettings::GetMetric(wxSYS_VSCROLL_X
);
636 // don't make the listbox too tall (limit height to 10 items) but don't
637 // make it too small neither
638 int hListbox
= SendMessage(GetHwnd(), LB_GETITEMHEIGHT
, 0, 0)*
639 wxMin(wxMax(m_noItems
, 3), 10);
641 return wxSize(wListbox
, hListbox
);
644 // ----------------------------------------------------------------------------
646 // ----------------------------------------------------------------------------
648 bool wxListBox::MSWCommand(WXUINT param
, WXWORD
WXUNUSED(id
))
650 if ((param
== LBN_SELCHANGE
) && HasMultipleSelection())
658 if ( param
== LBN_SELCHANGE
)
660 evtType
= wxEVT_COMMAND_LISTBOX_SELECTED
;
661 n
= SendMessage(GetHwnd(), LB_GETCARETINDEX
, 0, 0);
663 // NB: conveniently enough, LB_ERR is the same as wxNOT_FOUND
665 else if ( param
== LBN_DBLCLK
)
667 evtType
= wxEVT_COMMAND_LISTBOX_DOUBLECLICKED
;
668 n
= HitTest(ScreenToClient(wxGetMousePosition()));
672 // some event we're not interested in
676 // retrieve the affected item
677 if ( n
== wxNOT_FOUND
)
680 wxCommandEvent
event(evtType
, m_windowId
);
681 event
.SetEventObject(this);
683 if ( HasClientObjectData() )
684 event
.SetClientObject( GetClientObject(n
) );
685 else if ( HasClientUntypedData() )
686 event
.SetClientData( GetClientData(n
) );
688 event
.SetString(GetString(n
));
691 return HandleWindowEvent(event
);
694 // ----------------------------------------------------------------------------
695 // owner-drawn list boxes support
696 // ----------------------------------------------------------------------------
698 #if wxUSE_OWNER_DRAWN
700 // misc overloaded methods
701 // -----------------------
703 bool wxListBox::SetFont(const wxFont
&font
)
705 if ( HasFlag(wxLB_OWNERDRAW
) )
707 const unsigned count
= m_aItems
.GetCount();
708 for ( unsigned i
= 0; i
< count
; i
++ )
709 m_aItems
[i
]->SetFont(font
);
712 wxListBoxBase::SetFont(font
);
717 bool wxListBox::GetItemRect(size_t n
, wxRect
& rect
) const
719 wxCHECK_MSG( IsValid(n
), false,
720 wxT("invalid index in wxListBox::GetItemRect") );
724 if ( ListBox_GetItemRect(GetHwnd(), n
, &rc
) != LB_ERR
)
726 rect
= wxRectFromRECT(rc
);
731 // couldn't retrieve rect: for example, item isn't visible
736 bool wxListBox::RefreshItem(size_t n
)
739 if ( !GetItemRect(n
, rect
) )
743 wxCopyRectToRECT(rect
, rc
);
745 return ::InvalidateRect((HWND
)GetHWND(), &rc
, FALSE
) == TRUE
;
754 // space beneath/above each row in pixels
755 static const int LISTBOX_EXTRA_SPACE
= 1;
757 } // anonymous namespace
759 // the height is the same for all items
760 // TODO should be changed for LBS_OWNERDRAWVARIABLE style listboxes
762 // NB: can't forward this to wxListBoxItem because LB_SETITEMDATA
763 // message is not yet sent when we get here!
764 bool wxListBox::MSWOnMeasure(WXMEASUREITEMSTRUCT
*item
)
766 // only owner-drawn control should receive this message
767 wxCHECK( HasFlag(wxLB_OWNERDRAW
), false );
769 MEASUREITEMSTRUCT
*pStruct
= (MEASUREITEMSTRUCT
*)item
;
772 HDC hdc
= GetDC(NULL
);
774 HDC hdc
= CreateIC(wxT("DISPLAY"), NULL
, NULL
, 0);
778 wxDCTemp
dc((WXHDC
)hdc
);
779 dc
.SetFont(GetFont());
781 pStruct
->itemHeight
= dc
.GetCharHeight() + 2 * LISTBOX_EXTRA_SPACE
;
782 pStruct
->itemWidth
= dc
.GetCharWidth();
786 ReleaseDC(NULL
, hdc
);
794 // forward the message to the appropriate item
795 bool wxListBox::MSWOnDraw(WXDRAWITEMSTRUCT
*item
)
797 // only owner-drawn control should receive this message
798 wxCHECK( HasFlag(wxLB_OWNERDRAW
), false );
800 DRAWITEMSTRUCT
*pStruct
= (DRAWITEMSTRUCT
*)item
;
802 // the item may be -1 for an empty listbox
803 if ( pStruct
->itemID
== (UINT
)-1 )
806 wxListBoxItem
*pItem
= (wxListBoxItem
*)m_aItems
[pStruct
->itemID
];
808 wxDCTemp
dc((WXHDC
)pStruct
->hDC
);
810 return pItem
->OnDrawItem(dc
, wxRectFromRECT(pStruct
->rcItem
),
811 (wxOwnerDrawn::wxODAction
)pStruct
->itemAction
,
812 (wxOwnerDrawn::wxODStatus
)(pStruct
->itemState
| wxOwnerDrawn::wxODHidePrefix
));
815 #endif // wxUSE_OWNER_DRAWN
817 #endif // wxUSE_LISTBOX