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;
87 m_selectedByKeyboard
= false;
90 bool wxListBox::Create(wxWindow
*parent
,
94 int n
, const wxString choices
[],
96 const wxValidator
& validator
,
99 // initialize base class fields
100 if ( !CreateControl(parent
, id
, pos
, size
, style
, validator
, name
) )
103 // create the native control
104 if ( !MSWCreateControl(wxT("LISTBOX"), wxEmptyString
, pos
, size
) )
106 // control creation failed
110 // initialize the contents
111 for ( int i
= 0; i
< n
; i
++ )
116 // now we can compute our best size correctly, so do it again
117 SetInitialSize(size
);
122 bool wxListBox::Create(wxWindow
*parent
,
126 const wxArrayString
& choices
,
128 const wxValidator
& validator
,
129 const wxString
& name
)
131 wxCArrayString
chs(choices
);
132 return Create(parent
, id
, pos
, size
, chs
.GetCount(), chs
.GetStrings(),
133 style
, validator
, name
);
136 wxListBox::~wxListBox()
141 WXDWORD
wxListBox::MSWGetStyle(long style
, WXDWORD
*exstyle
) const
143 WXDWORD msStyle
= wxControl::MSWGetStyle(style
, exstyle
);
145 // we always want to get the notifications
146 msStyle
|= LBS_NOTIFY
;
148 // without this style, you get unexpected heights, so e.g. constraint
149 // layout doesn't work properly
150 msStyle
|= LBS_NOINTEGRALHEIGHT
;
152 wxASSERT_MSG( !(style
& wxLB_MULTIPLE
) || !(style
& wxLB_EXTENDED
),
153 wxT("only one of listbox selection modes can be specified") );
155 if ( style
& wxLB_MULTIPLE
)
156 msStyle
|= LBS_MULTIPLESEL
;
157 else if ( style
& wxLB_EXTENDED
)
158 msStyle
|= LBS_EXTENDEDSEL
;
160 wxASSERT_MSG( !(style
& wxLB_ALWAYS_SB
) || !(style
& wxLB_NO_SB
),
161 wxT( "Conflicting styles wxLB_ALWAYS_SB and wxLB_NO_SB." ) );
163 if ( !(style
& wxLB_NO_SB
) )
165 msStyle
|= WS_VSCROLL
;
166 if ( style
& wxLB_ALWAYS_SB
)
167 msStyle
|= LBS_DISABLENOSCROLL
;
170 if ( m_windowStyle
& wxLB_HSCROLL
)
171 msStyle
|= WS_HSCROLL
;
172 if ( m_windowStyle
& wxLB_SORT
)
175 #if wxUSE_OWNER_DRAWN && !defined(__WXWINCE__)
176 if ( m_windowStyle
& wxLB_OWNERDRAW
)
178 // we don't support LBS_OWNERDRAWVARIABLE yet and we also always put
179 // the strings in the listbox for simplicity even though we could have
180 // avoided it in this case
181 msStyle
|= LBS_OWNERDRAWFIXED
| LBS_HASSTRINGS
;
183 #endif // wxUSE_OWNER_DRAWN
188 void wxListBox::OnInternalIdle()
190 wxWindow::OnInternalIdle();
192 if (m_updateHorizontalExtent
)
194 SetHorizontalExtent(wxEmptyString
);
195 m_updateHorizontalExtent
= false;
199 void wxListBox::MSWOnItemsChanged()
201 // we need to do two things when items change: update their max horizontal
202 // extent so that horizontal scrollbar could be shown or hidden as
203 // appropriate and also invlaidate the best size
205 // updating the max extent is slow (it's an O(N) operation) and so we defer
206 // it until the idle time but the best size should be invalidated
207 // immediately doing it in idle time is too late -- layout using incorrect
208 // old best size will have been already done by then
210 m_updateHorizontalExtent
= true;
212 InvalidateBestSize();
215 // ----------------------------------------------------------------------------
216 // implementation of wxListBoxBase methods
217 // ----------------------------------------------------------------------------
219 void wxListBox::DoSetFirstItem(int N
)
221 wxCHECK_RET( IsValid(N
),
222 wxT("invalid index in wxListBox::SetFirstItem") );
224 SendMessage(GetHwnd(), LB_SETTOPINDEX
, (WPARAM
)N
, (LPARAM
)0);
227 void wxListBox::DoDeleteOneItem(unsigned int n
)
229 wxCHECK_RET( IsValid(n
),
230 wxT("invalid index in wxListBox::Delete") );
232 #if wxUSE_OWNER_DRAWN
233 if ( HasFlag(wxLB_OWNERDRAW
) )
236 m_aItems
.RemoveAt(n
);
238 #endif // wxUSE_OWNER_DRAWN
240 SendMessage(GetHwnd(), LB_DELETESTRING
, n
, 0);
245 UpdateOldSelections();
248 int wxListBox::FindString(const wxString
& s
, bool bCase
) const
250 // back to base class search for not native search type
252 return wxItemContainerImmutable::FindString( s
, bCase
);
254 int pos
= ListBox_FindStringExact(GetHwnd(), -1, s
.wx_str());
261 void wxListBox::DoClear()
263 #if wxUSE_OWNER_DRAWN
264 if ( HasFlag(wxLB_OWNERDRAW
) )
266 WX_CLEAR_ARRAY(m_aItems
);
268 #endif // wxUSE_OWNER_DRAWN
270 ListBox_ResetContent(GetHwnd());
275 UpdateOldSelections();
278 void wxListBox::DoSetSelection(int N
, bool select
)
280 wxCHECK_RET( N
== wxNOT_FOUND
|| IsValid(N
),
281 wxT("invalid index in wxListBox::SetSelection") );
283 if ( HasMultipleSelection() )
285 // Setting selection to -1 should deselect everything.
286 const bool deselectAll
= N
== wxNOT_FOUND
;
287 SendMessage(GetHwnd(), LB_SETSEL
,
288 deselectAll
? FALSE
: select
,
289 deselectAll
? -1 : N
);
293 SendMessage(GetHwnd(), LB_SETCURSEL
, select
? N
: -1, 0);
296 UpdateOldSelections();
299 bool wxListBox::IsSelected(int N
) const
301 wxCHECK_MSG( IsValid(N
), false,
302 wxT("invalid index in wxListBox::Selected") );
304 return SendMessage(GetHwnd(), LB_GETSEL
, N
, 0) == 0 ? false : true;
307 void *wxListBox::DoGetItemClientData(unsigned int n
) const
309 wxCHECK_MSG( IsValid(n
), NULL
,
310 wxT("invalid index in wxListBox::GetClientData") );
312 return (void *)SendMessage(GetHwnd(), LB_GETITEMDATA
, n
, 0);
315 void wxListBox::DoSetItemClientData(unsigned int n
, void *clientData
)
317 wxCHECK_RET( IsValid(n
),
318 wxT("invalid index in wxListBox::SetClientData") );
320 if ( ListBox_SetItemData(GetHwnd(), n
, clientData
) == LB_ERR
)
322 wxLogDebug(wxT("LB_SETITEMDATA failed"));
326 // Return number of selections and an array of selected integers
327 int wxListBox::GetSelections(wxArrayInt
& aSelections
) const
331 if ( HasMultipleSelection() )
333 int countSel
= ListBox_GetSelCount(GetHwnd());
334 if ( countSel
== LB_ERR
)
336 wxLogDebug(wxT("ListBox_GetSelCount failed"));
338 else if ( countSel
!= 0 )
340 int *selections
= new int[countSel
];
342 if ( ListBox_GetSelItems(GetHwnd(),
343 countSel
, selections
) == LB_ERR
)
345 wxLogDebug(wxT("ListBox_GetSelItems failed"));
350 aSelections
.Alloc(countSel
);
351 for ( int n
= 0; n
< countSel
; n
++ )
352 aSelections
.Add(selections
[n
]);
355 delete [] selections
;
360 else // single-selection listbox
362 if (ListBox_GetCurSel(GetHwnd()) > -1)
363 aSelections
.Add(ListBox_GetCurSel(GetHwnd()));
365 return aSelections
.Count();
369 // Get single selection, for single choice list items
370 int wxListBox::GetSelection() const
372 wxCHECK_MSG( !HasMultipleSelection(),
374 wxT("GetSelection() can't be used with multiple-selection listboxes, use GetSelections() instead.") );
376 return ListBox_GetCurSel(GetHwnd());
379 // Find string for position
380 wxString
wxListBox::GetString(unsigned int n
) const
382 wxCHECK_MSG( IsValid(n
), wxEmptyString
,
383 wxT("invalid index in wxListBox::GetString") );
385 int len
= ListBox_GetTextLen(GetHwnd(), n
);
387 // +1 for terminating NUL
389 ListBox_GetText(GetHwnd(), n
, (wxChar
*)wxStringBuffer(result
, len
+ 1));
394 int wxListBox::DoInsertItems(const wxArrayStringsAdapter
& items
,
397 wxClientDataType type
)
399 MSWAllocStorage(items
, LB_INITSTORAGE
);
401 const bool append
= pos
== GetCount();
403 // we must use CB_ADDSTRING when appending as only it works correctly for
404 // the sorted controls
405 const unsigned msg
= append
? LB_ADDSTRING
: LB_INSERTSTRING
;
412 const unsigned int numItems
= items
.GetCount();
413 for ( unsigned int i
= 0; i
< numItems
; i
++ )
415 n
= MSWInsertOrAppendItem(pos
, items
[i
], msg
);
416 if ( n
== wxNOT_FOUND
)
424 #if wxUSE_OWNER_DRAWN
425 if ( HasFlag(wxLB_OWNERDRAW
) )
427 wxOwnerDrawn
*pNewItem
= CreateLboxItem(n
);
428 pNewItem
->SetFont(GetFont());
429 m_aItems
.Insert(pNewItem
, n
);
431 #endif // wxUSE_OWNER_DRAWN
432 AssignNewItemClientData(n
, clientData
, i
, type
);
437 UpdateOldSelections();
442 int wxListBox::DoHitTestList(const wxPoint
& point
) const
444 LRESULT lRes
= ::SendMessage(GetHwnd(), LB_ITEMFROMPOINT
,
445 0, MAKELPARAM(point
.x
, point
.y
));
447 // non zero high-order word means that this item is outside of the client
448 // area, IOW the point is outside of the listbox
449 return HIWORD(lRes
) ? wxNOT_FOUND
: LOWORD(lRes
);
452 void wxListBox::SetString(unsigned int n
, const wxString
& s
)
454 wxCHECK_RET( IsValid(n
),
455 wxT("invalid index in wxListBox::SetString") );
457 // remember the state of the item
458 bool wasSelected
= IsSelected(n
);
460 void *oldData
= NULL
;
461 wxClientData
*oldObjData
= NULL
;
462 if ( HasClientUntypedData() )
463 oldData
= GetClientData(n
);
464 else if ( HasClientObjectData() )
465 oldObjData
= GetClientObject(n
);
467 // delete and recreate it
468 SendMessage(GetHwnd(), LB_DELETESTRING
, n
, 0);
471 if ( n
== (m_noItems
- 1) )
474 ListBox_InsertString(GetHwnd(), newN
, s
.wx_str());
476 // restore the client data
478 SetClientData(n
, oldData
);
479 else if ( oldObjData
)
480 SetClientObject(n
, oldObjData
);
482 // we may have lost the selection
489 unsigned int wxListBox::GetCount() const
494 // ----------------------------------------------------------------------------
495 // size-related stuff
496 // ----------------------------------------------------------------------------
498 void wxListBox::SetHorizontalExtent(const wxString
& s
)
500 // the rest is only necessary if we want a horizontal scrollbar
501 if ( !HasFlag(wxHSCROLL
) )
505 WindowHDC
dc(GetHwnd());
506 SelectInHDC
selFont(dc
, GetHfontOf(GetFont()));
508 TEXTMETRIC lpTextMetric
;
509 ::GetTextMetrics(dc
, &lpTextMetric
);
511 int largestExtent
= 0;
516 // set extent to the max length of all strings
517 for ( unsigned int i
= 0; i
< m_noItems
; i
++ )
519 const wxString str
= GetString(i
);
520 ::GetTextExtentPoint32(dc
, str
.c_str(), str
.length(), &extentXY
);
522 int extentX
= (int)(extentXY
.cx
+ lpTextMetric
.tmAveCharWidth
);
523 if ( extentX
> largestExtent
)
524 largestExtent
= extentX
;
527 else // just increase the extent to the length of this string
529 int existingExtent
= (int)SendMessage(GetHwnd(),
530 LB_GETHORIZONTALEXTENT
, 0, 0L);
532 ::GetTextExtentPoint32(dc
, s
.c_str(), s
.length(), &extentXY
);
534 int extentX
= (int)(extentXY
.cx
+ lpTextMetric
.tmAveCharWidth
);
535 if ( extentX
> existingExtent
)
536 largestExtent
= extentX
;
540 SendMessage(GetHwnd(), LB_SETHORIZONTALEXTENT
, LOWORD(largestExtent
), 0L);
541 //else: it shouldn't change
544 wxSize
wxListBox::DoGetBestClientSize() const
546 // find the widest string
549 for (unsigned int i
= 0; i
< m_noItems
; i
++)
551 wxString
str(GetString(i
));
552 GetTextExtent(str
, &wLine
, NULL
);
553 if ( wLine
> wListbox
)
557 // give it some reasonable default value if there are no strings in the
562 // the listbox should be slightly larger than the widest string
563 wListbox
+= 3*GetCharWidth();
565 // add room for the scrollbar
566 wListbox
+= wxSystemSettings::GetMetric(wxSYS_VSCROLL_X
);
568 // don't make the listbox too tall (limit height to 10 items) but don't
569 // make it too small neither
570 int hListbox
= SendMessage(GetHwnd(), LB_GETITEMHEIGHT
, 0, 0)*
571 wxMin(wxMax(m_noItems
, 3), 10);
573 return wxSize(wListbox
, hListbox
);
576 // ----------------------------------------------------------------------------
578 // ----------------------------------------------------------------------------
580 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 if ( m_selectedByKeyboard
)
593 // We shouldn't use the mouse position to find the item as mouse
594 // can be anywhere, ask the listbox itself. Notice that this can't
595 // be used when the item is selected using the mouse however as
596 // LB_GETCARETINDEX will always return a valid item, even if the
597 // mouse is clicked below all the items, which is why we find the
598 // item ourselves below in this case.
599 n
= SendMessage(GetHwnd(), LB_GETCARETINDEX
, 0, 0);
601 //else: n will be determined below from the mouse position
603 else if ( param
== LBN_DBLCLK
)
605 evtType
= wxEVT_COMMAND_LISTBOX_DOUBLECLICKED
;
609 // some event we're not interested in
613 // Find the item position if it was a mouse-generated selection event or a
614 // double click event (which is always generated using the mouse)
615 if ( n
== wxNOT_FOUND
)
617 const DWORD pos
= ::GetMessagePos();
618 const wxPoint
pt(GET_X_LPARAM(pos
), GET_Y_LPARAM(pos
));
619 n
= HitTest(ScreenToClient(wxPoint(pt
)));
622 // We get events even when mouse is clicked outside of any valid item from
623 // Windows, just ignore them.
624 if ( n
== wxNOT_FOUND
)
627 if ( param
== LBN_SELCHANGE
)
629 if ( !DoChangeSingleSelection(n
) )
633 // Do generate an event otherwise.
634 return SendEvent(evtType
, n
, true /* selection */);
638 wxListBox::MSWWindowProc(WXUINT nMsg
, WXWPARAM wParam
, WXLPARAM lParam
)
640 // Remember whether there was a keyboard or mouse event before
641 // LBN_SELCHANGE: this allows us to correctly determine the item affected
642 // by it in MSWCommand() above in any case.
643 if ( WM_KEYFIRST
<= nMsg
&& nMsg
<= WM_KEYLAST
)
644 m_selectedByKeyboard
= true;
645 else if ( WM_MOUSEFIRST
<= nMsg
&& nMsg
<= WM_MOUSELAST
)
646 m_selectedByKeyboard
= false;
648 return wxListBoxBase::MSWWindowProc(nMsg
, wParam
, lParam
);
651 // ----------------------------------------------------------------------------
652 // owner-drawn list boxes support
653 // ----------------------------------------------------------------------------
655 #if wxUSE_OWNER_DRAWN
657 // misc overloaded methods
658 // -----------------------
660 bool wxListBox::SetFont(const wxFont
&font
)
662 if ( HasFlag(wxLB_OWNERDRAW
) )
664 const unsigned count
= m_aItems
.GetCount();
665 for ( unsigned i
= 0; i
< count
; i
++ )
666 m_aItems
[i
]->SetFont(font
);
669 wxListBoxBase::SetFont(font
);
674 bool wxListBox::GetItemRect(size_t n
, wxRect
& rect
) const
676 wxCHECK_MSG( IsValid(n
), false,
677 wxT("invalid index in wxListBox::GetItemRect") );
681 if ( ListBox_GetItemRect(GetHwnd(), n
, &rc
) != LB_ERR
)
683 rect
= wxRectFromRECT(rc
);
688 // couldn't retrieve rect: for example, item isn't visible
693 bool wxListBox::RefreshItem(size_t n
)
696 if ( !GetItemRect(n
, rect
) )
700 wxCopyRectToRECT(rect
, rc
);
702 return ::InvalidateRect((HWND
)GetHWND(), &rc
, FALSE
) == TRUE
;
711 // space beneath/above each row in pixels
712 static const int LISTBOX_EXTRA_SPACE
= 1;
714 } // anonymous namespace
716 // the height is the same for all items
717 // TODO should be changed for LBS_OWNERDRAWVARIABLE style listboxes
719 // NB: can't forward this to wxListBoxItem because LB_SETITEMDATA
720 // message is not yet sent when we get here!
721 bool wxListBox::MSWOnMeasure(WXMEASUREITEMSTRUCT
*item
)
723 // only owner-drawn control should receive this message
724 wxCHECK( HasFlag(wxLB_OWNERDRAW
), false );
726 MEASUREITEMSTRUCT
*pStruct
= (MEASUREITEMSTRUCT
*)item
;
729 HDC hdc
= GetDC(NULL
);
731 HDC hdc
= CreateIC(wxT("DISPLAY"), NULL
, NULL
, 0);
735 wxDCTemp
dc((WXHDC
)hdc
);
736 dc
.SetFont(GetFont());
738 pStruct
->itemHeight
= dc
.GetCharHeight() + 2 * LISTBOX_EXTRA_SPACE
;
739 pStruct
->itemWidth
= dc
.GetCharWidth();
743 ReleaseDC(NULL
, hdc
);
751 // forward the message to the appropriate item
752 bool wxListBox::MSWOnDraw(WXDRAWITEMSTRUCT
*item
)
754 // only owner-drawn control should receive this message
755 wxCHECK( HasFlag(wxLB_OWNERDRAW
), false );
757 DRAWITEMSTRUCT
*pStruct
= (DRAWITEMSTRUCT
*)item
;
759 // the item may be -1 for an empty listbox
760 if ( pStruct
->itemID
== (UINT
)-1 )
763 wxListBoxItem
*pItem
= (wxListBoxItem
*)m_aItems
[pStruct
->itemID
];
765 wxDCTemp
dc((WXHDC
)pStruct
->hDC
);
767 return pItem
->OnDrawItem(dc
, wxRectFromRECT(pStruct
->rcItem
),
768 (wxOwnerDrawn::wxODAction
)pStruct
->itemAction
,
769 (wxOwnerDrawn::wxODStatus
)(pStruct
->itemState
| wxOwnerDrawn::wxODHidePrefix
));
772 #endif // wxUSE_OWNER_DRAWN
774 #endif // wxUSE_LISTBOX