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 // ----------------------------------------------------------------------------
152 void wxListBox::Init()
155 m_updateHorizontalExtent
= false;
158 bool wxListBox::Create(wxWindow
*parent
,
162 int n
, const wxString choices
[],
164 const wxValidator
& validator
,
165 const wxString
& name
)
167 // initialize base class fields
168 if ( !CreateControl(parent
, id
, pos
, size
, style
, validator
, name
) )
171 // create the native control
172 if ( !MSWCreateControl(wxT("LISTBOX"), wxEmptyString
, pos
, size
) )
174 // control creation failed
178 // initialize the contents
179 for ( int i
= 0; i
< n
; i
++ )
184 // now we can compute our best size correctly, so do it again
185 SetInitialSize(size
);
190 bool wxListBox::Create(wxWindow
*parent
,
194 const wxArrayString
& choices
,
196 const wxValidator
& validator
,
197 const wxString
& name
)
199 wxCArrayString
chs(choices
);
200 return Create(parent
, id
, pos
, size
, chs
.GetCount(), chs
.GetStrings(),
201 style
, validator
, name
);
204 wxListBox::~wxListBox()
209 WXDWORD
wxListBox::MSWGetStyle(long style
, WXDWORD
*exstyle
) const
211 WXDWORD msStyle
= wxControl::MSWGetStyle(style
, exstyle
);
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 wxT("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 wxASSERT_MSG( !(style
& wxLB_ALWAYS_SB
) || !(style
& wxLB_NO_SB
),
229 wxT( "Conflicting styles wxLB_ALWAYS_SB and wxLB_NO_SB." ) );
231 if ( !(style
& wxLB_NO_SB
) )
233 msStyle
|= WS_VSCROLL
;
234 if ( style
& wxLB_ALWAYS_SB
)
235 msStyle
|= LBS_DISABLENOSCROLL
;
238 if ( m_windowStyle
& wxLB_HSCROLL
)
239 msStyle
|= WS_HSCROLL
;
240 if ( m_windowStyle
& wxLB_SORT
)
243 #if wxUSE_OWNER_DRAWN && !defined(__WXWINCE__)
244 if ( m_windowStyle
& wxLB_OWNERDRAW
)
246 // we don't support LBS_OWNERDRAWVARIABLE yet and we also always put
247 // the strings in the listbox for simplicity even though we could have
248 // avoided it in this case
249 msStyle
|= LBS_OWNERDRAWFIXED
| LBS_HASSTRINGS
;
251 #endif // wxUSE_OWNER_DRAWN
256 void wxListBox::OnInternalIdle()
258 wxWindow::OnInternalIdle();
260 if (m_updateHorizontalExtent
)
262 SetHorizontalExtent(wxEmptyString
);
263 m_updateHorizontalExtent
= false;
267 void wxListBox::MSWOnItemsChanged()
269 // we need to do two things when items change: update their max horizontal
270 // extent so that horizontal scrollbar could be shown or hidden as
271 // appropriate and also invlaidate the best size
273 // updating the max extent is slow (it's an O(N) operation) and so we defer
274 // it until the idle time but the best size should be invalidated
275 // immediately doing it in idle time is too late -- layout using incorrect
276 // old best size will have been already done by then
278 m_updateHorizontalExtent
= true;
280 InvalidateBestSize();
283 // ----------------------------------------------------------------------------
284 // implementation of wxListBoxBase methods
285 // ----------------------------------------------------------------------------
287 void wxListBox::DoSetFirstItem(int N
)
289 wxCHECK_RET( IsValid(N
),
290 wxT("invalid index in wxListBox::SetFirstItem") );
292 SendMessage(GetHwnd(), LB_SETTOPINDEX
, (WPARAM
)N
, (LPARAM
)0);
295 void wxListBox::DoDeleteOneItem(unsigned int n
)
297 wxCHECK_RET( IsValid(n
),
298 wxT("invalid index in wxListBox::Delete") );
300 #if wxUSE_OWNER_DRAWN
301 if ( HasFlag(wxLB_OWNERDRAW
) )
304 m_aItems
.RemoveAt(n
);
306 #endif // wxUSE_OWNER_DRAWN
308 SendMessage(GetHwnd(), LB_DELETESTRING
, n
, 0);
313 UpdateOldSelections();
316 int wxListBox::FindString(const wxString
& s
, bool bCase
) const
318 // back to base class search for not native search type
320 return wxItemContainerImmutable::FindString( s
, bCase
);
322 int pos
= ListBox_FindStringExact(GetHwnd(), -1, s
.wx_str());
329 void wxListBox::DoClear()
331 #if wxUSE_OWNER_DRAWN
332 if ( HasFlag(wxLB_OWNERDRAW
) )
334 WX_CLEAR_ARRAY(m_aItems
);
336 #endif // wxUSE_OWNER_DRAWN
338 ListBox_ResetContent(GetHwnd());
343 UpdateOldSelections();
346 void wxListBox::DoSetSelection(int N
, bool select
)
348 wxCHECK_RET( N
== wxNOT_FOUND
|| IsValid(N
),
349 wxT("invalid index in wxListBox::SetSelection") );
351 if ( HasMultipleSelection() )
353 SendMessage(GetHwnd(), LB_SETSEL
, select
, N
);
357 SendMessage(GetHwnd(), LB_SETCURSEL
, select
? N
: -1, 0);
360 UpdateOldSelections();
363 bool wxListBox::IsSelected(int N
) const
365 wxCHECK_MSG( IsValid(N
), false,
366 wxT("invalid index in wxListBox::Selected") );
368 return SendMessage(GetHwnd(), LB_GETSEL
, N
, 0) == 0 ? false : true;
371 void *wxListBox::DoGetItemClientData(unsigned int n
) const
373 wxCHECK_MSG( IsValid(n
), NULL
,
374 wxT("invalid index in wxListBox::GetClientData") );
376 return (void *)SendMessage(GetHwnd(), LB_GETITEMDATA
, n
, 0);
379 void wxListBox::DoSetItemClientData(unsigned int n
, void *clientData
)
381 wxCHECK_RET( IsValid(n
),
382 wxT("invalid index in wxListBox::SetClientData") );
384 if ( ListBox_SetItemData(GetHwnd(), n
, clientData
) == LB_ERR
)
386 wxLogDebug(wxT("LB_SETITEMDATA failed"));
390 // Return number of selections and an array of selected integers
391 int wxListBox::GetSelections(wxArrayInt
& aSelections
) const
395 if ( HasMultipleSelection() )
397 int countSel
= ListBox_GetSelCount(GetHwnd());
398 if ( countSel
== LB_ERR
)
400 wxLogDebug(wxT("ListBox_GetSelCount failed"));
402 else if ( countSel
!= 0 )
404 int *selections
= new int[countSel
];
406 if ( ListBox_GetSelItems(GetHwnd(),
407 countSel
, selections
) == LB_ERR
)
409 wxLogDebug(wxT("ListBox_GetSelItems failed"));
414 aSelections
.Alloc(countSel
);
415 for ( int n
= 0; n
< countSel
; n
++ )
416 aSelections
.Add(selections
[n
]);
419 delete [] selections
;
424 else // single-selection listbox
426 if (ListBox_GetCurSel(GetHwnd()) > -1)
427 aSelections
.Add(ListBox_GetCurSel(GetHwnd()));
429 return aSelections
.Count();
433 // Get single selection, for single choice list items
434 int wxListBox::GetSelection() const
436 wxCHECK_MSG( !HasMultipleSelection(),
438 wxT("GetSelection() can't be used with multiple-selection listboxes, use GetSelections() instead.") );
440 return ListBox_GetCurSel(GetHwnd());
443 // Find string for position
444 wxString
wxListBox::GetString(unsigned int n
) const
446 wxCHECK_MSG( IsValid(n
), wxEmptyString
,
447 wxT("invalid index in wxListBox::GetString") );
449 int len
= ListBox_GetTextLen(GetHwnd(), n
);
451 // +1 for terminating NUL
453 ListBox_GetText(GetHwnd(), n
, (wxChar
*)wxStringBuffer(result
, len
+ 1));
458 int wxListBox::DoInsertItems(const wxArrayStringsAdapter
& items
,
461 wxClientDataType type
)
463 MSWAllocStorage(items
, LB_INITSTORAGE
);
465 const bool append
= pos
== GetCount();
467 // we must use CB_ADDSTRING when appending as only it works correctly for
468 // the sorted controls
469 const unsigned msg
= append
? LB_ADDSTRING
: LB_INSERTSTRING
;
476 const unsigned int numItems
= items
.GetCount();
477 for ( unsigned int i
= 0; i
< numItems
; i
++ )
479 n
= MSWInsertOrAppendItem(pos
, items
[i
], msg
);
480 if ( n
== wxNOT_FOUND
)
488 #if wxUSE_OWNER_DRAWN
489 if ( HasFlag(wxLB_OWNERDRAW
) )
491 wxOwnerDrawn
*pNewItem
= CreateLboxItem(n
);
492 pNewItem
->SetFont(GetFont());
493 m_aItems
.Insert(pNewItem
, n
);
495 #endif // wxUSE_OWNER_DRAWN
496 AssignNewItemClientData(n
, clientData
, i
, type
);
501 UpdateOldSelections();
506 int wxListBox::DoHitTestList(const wxPoint
& point
) const
508 LRESULT lRes
= ::SendMessage(GetHwnd(), LB_ITEMFROMPOINT
,
509 0, MAKELPARAM(point
.x
, point
.y
));
511 // non zero high-order word means that this item is outside of the client
512 // area, IOW the point is outside of the listbox
513 return HIWORD(lRes
) ? wxNOT_FOUND
: LOWORD(lRes
);
516 void wxListBox::SetString(unsigned int n
, const wxString
& s
)
518 wxCHECK_RET( IsValid(n
),
519 wxT("invalid index in wxListBox::SetString") );
521 // remember the state of the item
522 bool wasSelected
= IsSelected(n
);
524 void *oldData
= NULL
;
525 wxClientData
*oldObjData
= NULL
;
526 if ( HasClientUntypedData() )
527 oldData
= GetClientData(n
);
528 else if ( HasClientObjectData() )
529 oldObjData
= GetClientObject(n
);
531 // delete and recreate it
532 SendMessage(GetHwnd(), LB_DELETESTRING
, n
, 0);
535 if ( n
== (m_noItems
- 1) )
538 ListBox_InsertString(GetHwnd(), newN
, s
.wx_str());
540 // restore the client data
542 SetClientData(n
, oldData
);
543 else if ( oldObjData
)
544 SetClientObject(n
, oldObjData
);
546 // we may have lost the selection
553 unsigned int wxListBox::GetCount() const
558 // ----------------------------------------------------------------------------
559 // size-related stuff
560 // ----------------------------------------------------------------------------
562 void wxListBox::SetHorizontalExtent(const wxString
& s
)
564 // the rest is only necessary if we want a horizontal scrollbar
565 if ( !HasFlag(wxHSCROLL
) )
569 WindowHDC
dc(GetHwnd());
570 SelectInHDC
selFont(dc
, GetHfontOf(GetFont()));
572 TEXTMETRIC lpTextMetric
;
573 ::GetTextMetrics(dc
, &lpTextMetric
);
575 int largestExtent
= 0;
580 // set extent to the max length of all strings
581 for ( unsigned int i
= 0; i
< m_noItems
; i
++ )
583 const wxString str
= GetString(i
);
584 ::GetTextExtentPoint32(dc
, str
.c_str(), str
.length(), &extentXY
);
586 int extentX
= (int)(extentXY
.cx
+ lpTextMetric
.tmAveCharWidth
);
587 if ( extentX
> largestExtent
)
588 largestExtent
= extentX
;
591 else // just increase the extent to the length of this string
593 int existingExtent
= (int)SendMessage(GetHwnd(),
594 LB_GETHORIZONTALEXTENT
, 0, 0L);
596 ::GetTextExtentPoint32(dc
, s
.c_str(), s
.length(), &extentXY
);
598 int extentX
= (int)(extentXY
.cx
+ lpTextMetric
.tmAveCharWidth
);
599 if ( extentX
> existingExtent
)
600 largestExtent
= extentX
;
604 SendMessage(GetHwnd(), LB_SETHORIZONTALEXTENT
, LOWORD(largestExtent
), 0L);
605 //else: it shouldn't change
608 wxSize
wxListBox::DoGetBestClientSize() const
610 // find the widest string
613 for (unsigned int i
= 0; i
< m_noItems
; i
++)
615 wxString
str(GetString(i
));
616 GetTextExtent(str
, &wLine
, NULL
);
617 if ( wLine
> wListbox
)
621 // give it some reasonable default value if there are no strings in the
626 // the listbox should be slightly larger than the widest string
627 wListbox
+= 3*GetCharWidth();
629 // add room for the scrollbar
630 wListbox
+= wxSystemSettings::GetMetric(wxSYS_VSCROLL_X
);
632 // don't make the listbox too tall (limit height to 10 items) but don't
633 // make it too small neither
634 int hListbox
= SendMessage(GetHwnd(), LB_GETITEMHEIGHT
, 0, 0)*
635 wxMin(wxMax(m_noItems
, 3), 10);
637 return wxSize(wListbox
, hListbox
);
640 // ----------------------------------------------------------------------------
642 // ----------------------------------------------------------------------------
644 bool wxListBox::MSWCommand(WXUINT param
, WXWORD
WXUNUSED(id
))
648 if ( param
== LBN_SELCHANGE
)
650 if ( HasMultipleSelection() )
651 return CalcAndSendEvent();
653 evtType
= wxEVT_COMMAND_LISTBOX_SELECTED
;
654 n
= SendMessage(GetHwnd(), LB_GETCARETINDEX
, 0, 0);
656 // NB: conveniently enough, LB_ERR is the same as wxNOT_FOUND
658 else if ( param
== LBN_DBLCLK
)
660 evtType
= wxEVT_COMMAND_LISTBOX_DOUBLECLICKED
;
661 n
= HitTest(ScreenToClient(wxGetMousePosition()));
665 // some event we're not interested in
669 // only send an event if we have a valid item
670 return n
!= wxNOT_FOUND
&& SendEvent(evtType
, n
, true /* selection */);
673 // ----------------------------------------------------------------------------
674 // owner-drawn list boxes support
675 // ----------------------------------------------------------------------------
677 #if wxUSE_OWNER_DRAWN
679 // misc overloaded methods
680 // -----------------------
682 bool wxListBox::SetFont(const wxFont
&font
)
684 if ( HasFlag(wxLB_OWNERDRAW
) )
686 const unsigned count
= m_aItems
.GetCount();
687 for ( unsigned i
= 0; i
< count
; i
++ )
688 m_aItems
[i
]->SetFont(font
);
691 wxListBoxBase::SetFont(font
);
696 bool wxListBox::GetItemRect(size_t n
, wxRect
& rect
) const
698 wxCHECK_MSG( IsValid(n
), false,
699 wxT("invalid index in wxListBox::GetItemRect") );
703 if ( ListBox_GetItemRect(GetHwnd(), n
, &rc
) != LB_ERR
)
705 rect
= wxRectFromRECT(rc
);
710 // couldn't retrieve rect: for example, item isn't visible
715 bool wxListBox::RefreshItem(size_t n
)
718 if ( !GetItemRect(n
, rect
) )
722 wxCopyRectToRECT(rect
, rc
);
724 return ::InvalidateRect((HWND
)GetHWND(), &rc
, FALSE
) == TRUE
;
733 // space beneath/above each row in pixels
734 static const int LISTBOX_EXTRA_SPACE
= 1;
736 } // anonymous namespace
738 // the height is the same for all items
739 // TODO should be changed for LBS_OWNERDRAWVARIABLE style listboxes
741 // NB: can't forward this to wxListBoxItem because LB_SETITEMDATA
742 // message is not yet sent when we get here!
743 bool wxListBox::MSWOnMeasure(WXMEASUREITEMSTRUCT
*item
)
745 // only owner-drawn control should receive this message
746 wxCHECK( HasFlag(wxLB_OWNERDRAW
), false );
748 MEASUREITEMSTRUCT
*pStruct
= (MEASUREITEMSTRUCT
*)item
;
751 HDC hdc
= GetDC(NULL
);
753 HDC hdc
= CreateIC(wxT("DISPLAY"), NULL
, NULL
, 0);
757 wxDCTemp
dc((WXHDC
)hdc
);
758 dc
.SetFont(GetFont());
760 pStruct
->itemHeight
= dc
.GetCharHeight() + 2 * LISTBOX_EXTRA_SPACE
;
761 pStruct
->itemWidth
= dc
.GetCharWidth();
765 ReleaseDC(NULL
, hdc
);
773 // forward the message to the appropriate item
774 bool wxListBox::MSWOnDraw(WXDRAWITEMSTRUCT
*item
)
776 // only owner-drawn control should receive this message
777 wxCHECK( HasFlag(wxLB_OWNERDRAW
), false );
779 DRAWITEMSTRUCT
*pStruct
= (DRAWITEMSTRUCT
*)item
;
781 // the item may be -1 for an empty listbox
782 if ( pStruct
->itemID
== (UINT
)-1 )
785 wxListBoxItem
*pItem
= (wxListBoxItem
*)m_aItems
[pStruct
->itemID
];
787 wxDCTemp
dc((WXHDC
)pStruct
->hDC
);
789 return pItem
->OnDrawItem(dc
, wxRectFromRECT(pStruct
->rcItem
),
790 (wxOwnerDrawn::wxODAction
)pStruct
->itemAction
,
791 (wxOwnerDrawn::wxODStatus
)(pStruct
->itemState
| wxOwnerDrawn::wxODHidePrefix
));
794 #endif // wxUSE_OWNER_DRAWN
796 #endif // wxUSE_LISTBOX