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 // ============================================================================
44 // list box item declaration and implementation
45 // ============================================================================
49 class wxListBoxItem
: public wxOwnerDrawn
52 wxListBoxItem(wxListBox
*parent
)
53 { m_parent
= parent
; }
55 wxListBox
*GetParent() const
59 { return m_parent
->GetItemIndex(const_cast<wxListBoxItem
*>(this)); }
61 wxString
GetName() const
62 { return m_parent
->GetString(GetIndex()); }
68 wxOwnerDrawn
*wxListBox::CreateLboxItem(size_t WXUNUSED(n
))
70 return new wxListBoxItem(this);
73 #endif //USE_OWNER_DRAWN
75 // ============================================================================
76 // list box control implementation
77 // ============================================================================
79 // ----------------------------------------------------------------------------
81 // ----------------------------------------------------------------------------
83 void wxListBox::Init()
86 m_updateHorizontalExtent
= false;
89 bool wxListBox::Create(wxWindow
*parent
,
93 int n
, const wxString choices
[],
95 const wxValidator
& validator
,
98 // initialize base class fields
99 if ( !CreateControl(parent
, id
, pos
, size
, style
, validator
, name
) )
102 // create the native control
103 if ( !MSWCreateControl(wxT("LISTBOX"), wxEmptyString
, pos
, size
) )
105 // control creation failed
109 // initialize the contents
110 for ( int i
= 0; i
< n
; i
++ )
115 // now we can compute our best size correctly, so do it again
116 SetInitialSize(size
);
121 bool wxListBox::Create(wxWindow
*parent
,
125 const wxArrayString
& choices
,
127 const wxValidator
& validator
,
128 const wxString
& name
)
130 wxCArrayString
chs(choices
);
131 return Create(parent
, id
, pos
, size
, chs
.GetCount(), chs
.GetStrings(),
132 style
, validator
, name
);
135 wxListBox::~wxListBox()
140 WXDWORD
wxListBox::MSWGetStyle(long style
, WXDWORD
*exstyle
) const
142 WXDWORD msStyle
= wxControl::MSWGetStyle(style
, exstyle
);
144 // we always want to get the notifications
145 msStyle
|= LBS_NOTIFY
;
147 // without this style, you get unexpected heights, so e.g. constraint
148 // layout doesn't work properly
149 msStyle
|= LBS_NOINTEGRALHEIGHT
;
151 wxASSERT_MSG( !(style
& wxLB_MULTIPLE
) || !(style
& wxLB_EXTENDED
),
152 wxT("only one of listbox selection modes can be specified") );
154 if ( style
& wxLB_MULTIPLE
)
155 msStyle
|= LBS_MULTIPLESEL
;
156 else if ( style
& wxLB_EXTENDED
)
157 msStyle
|= LBS_EXTENDEDSEL
;
159 wxASSERT_MSG( !(style
& wxLB_ALWAYS_SB
) || !(style
& wxLB_NO_SB
),
160 wxT( "Conflicting styles wxLB_ALWAYS_SB and wxLB_NO_SB." ) );
162 if ( !(style
& wxLB_NO_SB
) )
164 msStyle
|= WS_VSCROLL
;
165 if ( style
& wxLB_ALWAYS_SB
)
166 msStyle
|= LBS_DISABLENOSCROLL
;
169 if ( m_windowStyle
& wxLB_HSCROLL
)
170 msStyle
|= WS_HSCROLL
;
171 if ( m_windowStyle
& wxLB_SORT
)
174 #if wxUSE_OWNER_DRAWN && !defined(__WXWINCE__)
175 if ( m_windowStyle
& wxLB_OWNERDRAW
)
177 // we don't support LBS_OWNERDRAWVARIABLE yet and we also always put
178 // the strings in the listbox for simplicity even though we could have
179 // avoided it in this case
180 msStyle
|= LBS_OWNERDRAWFIXED
| LBS_HASSTRINGS
;
182 #endif // wxUSE_OWNER_DRAWN
187 void wxListBox::OnInternalIdle()
189 wxWindow::OnInternalIdle();
191 if (m_updateHorizontalExtent
)
193 SetHorizontalExtent(wxEmptyString
);
194 m_updateHorizontalExtent
= false;
198 void wxListBox::MSWOnItemsChanged()
200 // we need to do two things when items change: update their max horizontal
201 // extent so that horizontal scrollbar could be shown or hidden as
202 // appropriate and also invlaidate the best size
204 // updating the max extent is slow (it's an O(N) operation) and so we defer
205 // it until the idle time but the best size should be invalidated
206 // immediately doing it in idle time is too late -- layout using incorrect
207 // old best size will have been already done by then
209 m_updateHorizontalExtent
= true;
211 InvalidateBestSize();
214 // ----------------------------------------------------------------------------
215 // implementation of wxListBoxBase methods
216 // ----------------------------------------------------------------------------
218 void wxListBox::DoSetFirstItem(int N
)
220 wxCHECK_RET( IsValid(N
),
221 wxT("invalid index in wxListBox::SetFirstItem") );
223 SendMessage(GetHwnd(), LB_SETTOPINDEX
, (WPARAM
)N
, (LPARAM
)0);
226 void wxListBox::DoDeleteOneItem(unsigned int n
)
228 wxCHECK_RET( IsValid(n
),
229 wxT("invalid index in wxListBox::Delete") );
231 #if wxUSE_OWNER_DRAWN
232 if ( HasFlag(wxLB_OWNERDRAW
) )
235 m_aItems
.RemoveAt(n
);
237 #endif // wxUSE_OWNER_DRAWN
239 SendMessage(GetHwnd(), LB_DELETESTRING
, n
, 0);
244 UpdateOldSelections();
247 int wxListBox::FindString(const wxString
& s
, bool bCase
) const
249 // back to base class search for not native search type
251 return wxItemContainerImmutable::FindString( s
, bCase
);
253 int pos
= ListBox_FindStringExact(GetHwnd(), -1, s
.t_str());
260 void wxListBox::DoClear()
262 #if wxUSE_OWNER_DRAWN
263 if ( HasFlag(wxLB_OWNERDRAW
) )
265 WX_CLEAR_ARRAY(m_aItems
);
267 #endif // wxUSE_OWNER_DRAWN
269 ListBox_ResetContent(GetHwnd());
274 UpdateOldSelections();
277 void wxListBox::DoSetSelection(int N
, bool select
)
279 wxCHECK_RET( N
== wxNOT_FOUND
|| IsValid(N
),
280 wxT("invalid index in wxListBox::SetSelection") );
282 if ( HasMultipleSelection() )
284 // Setting selection to -1 should deselect everything.
285 const bool deselectAll
= N
== wxNOT_FOUND
;
286 SendMessage(GetHwnd(), LB_SETSEL
,
287 deselectAll
? FALSE
: select
,
288 deselectAll
? -1 : N
);
292 SendMessage(GetHwnd(), LB_SETCURSEL
, select
? N
: -1, 0);
295 UpdateOldSelections();
298 bool wxListBox::IsSelected(int N
) const
300 wxCHECK_MSG( IsValid(N
), false,
301 wxT("invalid index in wxListBox::Selected") );
303 return SendMessage(GetHwnd(), LB_GETSEL
, N
, 0) == 0 ? false : true;
306 void *wxListBox::DoGetItemClientData(unsigned int n
) const
308 LPARAM rc
= SendMessage(GetHwnd(), LB_GETITEMDATA
, n
, 0);
309 if ( rc
== LB_ERR
&& GetLastError() != ERROR_SUCCESS
)
311 wxLogLastError(wxT("LB_GETITEMDATA"));
319 void wxListBox::DoSetItemClientData(unsigned int n
, void *clientData
)
321 if ( ListBox_SetItemData(GetHwnd(), n
, clientData
) == LB_ERR
)
323 wxLogDebug(wxT("LB_SETITEMDATA failed"));
327 // Return number of selections and an array of selected integers
328 int wxListBox::GetSelections(wxArrayInt
& aSelections
) const
332 if ( HasMultipleSelection() )
334 int countSel
= ListBox_GetSelCount(GetHwnd());
335 if ( countSel
== LB_ERR
)
337 wxLogDebug(wxT("ListBox_GetSelCount failed"));
339 else if ( countSel
!= 0 )
341 int *selections
= new int[countSel
];
343 if ( ListBox_GetSelItems(GetHwnd(),
344 countSel
, selections
) == LB_ERR
)
346 wxLogDebug(wxT("ListBox_GetSelItems failed"));
351 aSelections
.Alloc(countSel
);
352 for ( int n
= 0; n
< countSel
; n
++ )
353 aSelections
.Add(selections
[n
]);
356 delete [] selections
;
361 else // single-selection listbox
363 if (ListBox_GetCurSel(GetHwnd()) > -1)
364 aSelections
.Add(ListBox_GetCurSel(GetHwnd()));
366 return aSelections
.Count();
370 // Get single selection, for single choice list items
371 int wxListBox::GetSelection() const
373 wxCHECK_MSG( !HasMultipleSelection(),
375 wxT("GetSelection() can't be used with multiple-selection listboxes, use GetSelections() instead.") );
377 return ListBox_GetCurSel(GetHwnd());
380 // Find string for position
381 wxString
wxListBox::GetString(unsigned int n
) const
383 wxCHECK_MSG( IsValid(n
), wxEmptyString
,
384 wxT("invalid index in wxListBox::GetString") );
386 int len
= ListBox_GetTextLen(GetHwnd(), n
);
388 // +1 for terminating NUL
390 ListBox_GetText(GetHwnd(), n
, (wxChar
*)wxStringBuffer(result
, len
+ 1));
395 int wxListBox::DoInsertItems(const wxArrayStringsAdapter
& items
,
398 wxClientDataType type
)
400 MSWAllocStorage(items
, LB_INITSTORAGE
);
402 const bool append
= pos
== GetCount();
404 // we must use CB_ADDSTRING when appending as only it works correctly for
405 // the sorted controls
406 const unsigned msg
= append
? LB_ADDSTRING
: LB_INSERTSTRING
;
413 const unsigned int numItems
= items
.GetCount();
414 for ( unsigned int i
= 0; i
< numItems
; i
++ )
416 n
= MSWInsertOrAppendItem(pos
, items
[i
], msg
);
417 if ( n
== wxNOT_FOUND
)
425 #if wxUSE_OWNER_DRAWN
426 if ( HasFlag(wxLB_OWNERDRAW
) )
428 wxOwnerDrawn
*pNewItem
= CreateLboxItem(n
);
429 pNewItem
->SetFont(GetFont());
430 m_aItems
.Insert(pNewItem
, n
);
432 #endif // wxUSE_OWNER_DRAWN
433 AssignNewItemClientData(n
, clientData
, i
, type
);
438 UpdateOldSelections();
443 int wxListBox::DoHitTestList(const wxPoint
& point
) const
445 LRESULT lRes
= ::SendMessage(GetHwnd(), LB_ITEMFROMPOINT
,
446 0, MAKELPARAM(point
.x
, point
.y
));
448 // non zero high-order word means that this item is outside of the client
449 // area, IOW the point is outside of the listbox
450 return HIWORD(lRes
) ? wxNOT_FOUND
: LOWORD(lRes
);
453 void wxListBox::SetString(unsigned int n
, const wxString
& s
)
455 wxCHECK_RET( IsValid(n
),
456 wxT("invalid index in wxListBox::SetString") );
458 // remember the state of the item
459 bool wasSelected
= IsSelected(n
);
461 void *oldData
= NULL
;
462 wxClientData
*oldObjData
= NULL
;
463 if ( HasClientUntypedData() )
464 oldData
= GetClientData(n
);
465 else if ( HasClientObjectData() )
466 oldObjData
= GetClientObject(n
);
468 // delete and recreate it
469 SendMessage(GetHwnd(), LB_DELETESTRING
, n
, 0);
472 if ( n
== (m_noItems
- 1) )
475 ListBox_InsertString(GetHwnd(), newN
, s
.t_str());
477 // restore the client data
479 SetClientData(n
, oldData
);
480 else if ( oldObjData
)
481 SetClientObject(n
, oldObjData
);
483 // we may have lost the selection
490 unsigned int wxListBox::GetCount() const
495 // ----------------------------------------------------------------------------
496 // size-related stuff
497 // ----------------------------------------------------------------------------
499 void wxListBox::SetHorizontalExtent(const wxString
& s
)
501 // the rest is only necessary if we want a horizontal scrollbar
502 if ( !HasFlag(wxHSCROLL
) )
506 WindowHDC
dc(GetHwnd());
507 SelectInHDC
selFont(dc
, GetHfontOf(GetFont()));
509 TEXTMETRIC lpTextMetric
;
510 ::GetTextMetrics(dc
, &lpTextMetric
);
512 int largestExtent
= 0;
517 // set extent to the max length of all strings
518 for ( unsigned int i
= 0; i
< m_noItems
; i
++ )
520 const wxString str
= GetString(i
);
521 ::GetTextExtentPoint32(dc
, str
.c_str(), str
.length(), &extentXY
);
523 int extentX
= (int)(extentXY
.cx
+ lpTextMetric
.tmAveCharWidth
);
524 if ( extentX
> largestExtent
)
525 largestExtent
= extentX
;
528 else // just increase the extent to the length of this string
530 int existingExtent
= (int)SendMessage(GetHwnd(),
531 LB_GETHORIZONTALEXTENT
, 0, 0L);
533 ::GetTextExtentPoint32(dc
, s
.c_str(), s
.length(), &extentXY
);
535 int extentX
= (int)(extentXY
.cx
+ lpTextMetric
.tmAveCharWidth
);
536 if ( extentX
> existingExtent
)
537 largestExtent
= extentX
;
541 SendMessage(GetHwnd(), LB_SETHORIZONTALEXTENT
, LOWORD(largestExtent
), 0L);
542 //else: it shouldn't change
545 wxSize
wxListBox::DoGetBestClientSize() const
547 // find the widest string
550 for (unsigned int i
= 0; i
< m_noItems
; i
++)
552 wxString
str(GetString(i
));
553 GetTextExtent(str
, &wLine
, NULL
);
554 if ( wLine
> wListbox
)
558 // give it some reasonable default value if there are no strings in the
563 // the listbox should be slightly larger than the widest string
564 wListbox
+= 3*GetCharWidth();
566 // add room for the scrollbar
567 wListbox
+= wxSystemSettings::GetMetric(wxSYS_VSCROLL_X
);
569 // don't make the listbox too tall (limit height to 10 items) but don't
570 // make it too small neither
571 int hListbox
= SendMessage(GetHwnd(), LB_GETITEMHEIGHT
, 0, 0)*
572 wxMin(wxMax(m_noItems
, 3), 10);
574 return wxSize(wListbox
, hListbox
);
577 // ----------------------------------------------------------------------------
579 // ----------------------------------------------------------------------------
581 bool wxListBox::MSWCommand(WXUINT param
, WXWORD
WXUNUSED(id
))
584 if ( param
== LBN_SELCHANGE
)
586 if ( HasMultipleSelection() )
587 return CalcAndSendEvent();
589 evtType
= wxEVT_COMMAND_LISTBOX_SELECTED
;
591 else if ( param
== LBN_DBLCLK
)
593 // Clicking under the last item in the listbox generates double click
594 // event for the currently selected item which is rather surprising.
595 // Avoid the surprise by checking that we do have an item under mouse.
596 const DWORD pos
= ::GetMessagePos();
597 const wxPoint
pt(GET_X_LPARAM(pos
), GET_Y_LPARAM(pos
));
598 if ( HitTest(ScreenToClient(pt
)) == wxNOT_FOUND
)
601 evtType
= wxEVT_COMMAND_LISTBOX_DOUBLECLICKED
;
605 // some event we're not interested in
609 const int n
= ListBox_GetCurSel(GetHwnd());
611 // We get events even when mouse is clicked outside of any valid item from
612 // Windows, just ignore them.
613 if ( n
== wxNOT_FOUND
)
616 if ( param
== LBN_SELCHANGE
)
618 if ( !DoChangeSingleSelection(n
) )
622 // Do generate an event otherwise.
623 return SendEvent(evtType
, n
, true /* selection */);
626 // ----------------------------------------------------------------------------
627 // owner-drawn list boxes support
628 // ----------------------------------------------------------------------------
630 #if wxUSE_OWNER_DRAWN
632 // misc overloaded methods
633 // -----------------------
635 bool wxListBox::SetFont(const wxFont
&font
)
637 if ( HasFlag(wxLB_OWNERDRAW
) )
639 const unsigned count
= m_aItems
.GetCount();
640 for ( unsigned i
= 0; i
< count
; i
++ )
641 m_aItems
[i
]->SetFont(font
);
644 wxListBoxBase::SetFont(font
);
649 bool wxListBox::GetItemRect(size_t n
, wxRect
& rect
) const
651 wxCHECK_MSG( IsValid(n
), false,
652 wxT("invalid index in wxListBox::GetItemRect") );
656 if ( ListBox_GetItemRect(GetHwnd(), n
, &rc
) != LB_ERR
)
658 rect
= wxRectFromRECT(rc
);
663 // couldn't retrieve rect: for example, item isn't visible
668 bool wxListBox::RefreshItem(size_t n
)
671 if ( !GetItemRect(n
, rect
) )
675 wxCopyRectToRECT(rect
, rc
);
677 return ::InvalidateRect((HWND
)GetHWND(), &rc
, FALSE
) == TRUE
;
686 // space beneath/above each row in pixels
687 static const int LISTBOX_EXTRA_SPACE
= 1;
689 } // anonymous namespace
691 // the height is the same for all items
692 // TODO should be changed for LBS_OWNERDRAWVARIABLE style listboxes
694 // NB: can't forward this to wxListBoxItem because LB_SETITEMDATA
695 // message is not yet sent when we get here!
696 bool wxListBox::MSWOnMeasure(WXMEASUREITEMSTRUCT
*item
)
698 // only owner-drawn control should receive this message
699 wxCHECK( HasFlag(wxLB_OWNERDRAW
), false );
701 MEASUREITEMSTRUCT
*pStruct
= (MEASUREITEMSTRUCT
*)item
;
704 HDC hdc
= GetDC(NULL
);
706 HDC hdc
= CreateIC(wxT("DISPLAY"), NULL
, NULL
, 0);
710 wxDCTemp
dc((WXHDC
)hdc
);
711 dc
.SetFont(GetFont());
713 pStruct
->itemHeight
= dc
.GetCharHeight() + 2 * LISTBOX_EXTRA_SPACE
;
714 pStruct
->itemWidth
= dc
.GetCharWidth();
718 ReleaseDC(NULL
, hdc
);
726 // forward the message to the appropriate item
727 bool wxListBox::MSWOnDraw(WXDRAWITEMSTRUCT
*item
)
729 // only owner-drawn control should receive this message
730 wxCHECK( HasFlag(wxLB_OWNERDRAW
), false );
732 DRAWITEMSTRUCT
*pStruct
= (DRAWITEMSTRUCT
*)item
;
734 // the item may be -1 for an empty listbox
735 if ( pStruct
->itemID
== (UINT
)-1 )
738 wxListBoxItem
*pItem
= (wxListBoxItem
*)m_aItems
[pStruct
->itemID
];
740 wxDCTemp
dc((WXHDC
)pStruct
->hDC
);
742 return pItem
->OnDrawItem(dc
, wxRectFromRECT(pStruct
->rcItem
),
743 (wxOwnerDrawn::wxODAction
)pStruct
->itemAction
,
744 (wxOwnerDrawn::wxODStatus
)(pStruct
->itemState
| wxOwnerDrawn::wxODHidePrefix
));
747 #endif // wxUSE_OWNER_DRAWN
749 #endif // wxUSE_LISTBOX